leet-code/src/main/java/leetcode/editor/cn/BinaryTreePreorderTraversal.java
2021-04-29 23:21:52 +08:00

99 lines
1.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
//
//
//
// 示例 1
//
//
//输入root = [1,null,2,3]
//输出:[1,2,3]
//
//
// 示例 2
//
//
//输入root = []
//输出:[]
//
//
// 示例 3
//
//
//输入root = [1]
//输出:[1]
//
//
// 示例 4
//
//
//输入root = [1,2]
//输出:[1,2]
//
//
// 示例 5
//
//
//输入root = [1,null,2]
//输出:[1,2]
//
//
//
//
// 提示:
//
//
// 树中节点数目在范围 [0, 100] 内
// -100 <= Node.val <= 100
//
//
//
//
// 进阶:递归算法很简单,你可以通过迭代算法完成吗?
// Related Topics 栈 树
// 👍 552 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TreeNode;
import java.util.*;
//144:二叉树的前序遍历
public class BinaryTreePreorderTraversal {
public static void main(String[] args) {
//测试代码
Solution solution = new BinaryTreePreorderTraversal().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
list.add(root.val);
list.addAll(preorderTraversal(root.left));
list.addAll(preorderTraversal(root.right));
return list;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}