问题
给定一个二叉树,返回它的 前序 遍历。
例子
思路
- 递归 添加val->左结点遍历->右结点遍历
- 迭代 装Object的Stack 压栈顺序:右结点->左结点->new Integer(val)
- 迭代2
代码
//递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
preOrder(root, list);
return list;
}
public void preOrder(TreeNode root, List<Integer> list) {
if (root==null) return ;
list.add(root.val);
if (root.left!=null) preOrder(root.left,list);
if (root.right!=null) preOrder(root.right, list);
}
}
//迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (root==null) return new ArrayList();
List<Integer> list = new ArrayList<>();
Stack stack = new Stack();
stack.push(root);
while (!stack.isEmpty()) {
if (stack.peek() instanceof TreeNode) {
TreeNode node = (TreeNode)stack.pop();
if (node.right!=null) stack.push(node.right);
if (node.left!=null) stack.push(node.left);
stack.push(new Integer(node.val));
} else{
list.add((Integer)stack.pop());
}
}
return list;
}
}