题目:给你二叉树的根节点 root
,返回它节点值的 前序 **遍历。
示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]
思路:前序遍历:根-左-右。
这里我在实现时,被递归卡住了。主要原因是因为preorderTraversal的返回值是List,用该方法递归时,不知道递归左右子树时如何处理返回值。
/**
* 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> res = new ArrayList<>();
preorder(root,res);
return res;
}
public void preorder(TreeNode root,List<Integer> res) {
if(root == null ) {
return;
}
res.add(root.val);
preorder(root.left,res);
preorder(root.right,res);
}
}
注意:while循环时注意判断root != null;否则会出现空指针异常
/**
* 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> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty() && root != null){
TreeNode cur = stack.pop();
res.add(cur.val);
// 栈先进后出(后进先出),这里先放右子树,再放左子树
if(cur.right != null) {
stack.push(cur.right) ;
}
if(cur.left != null) {
stack.push(cur.left) ;
}
}
return res;
}
}