![](https://i-blog.csdnimg.cn/blog_migrate/2fc621fac674da33078853f931b5151b.png)
方法一:递归
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);
preorder(root.left, list);
preorder(root.right, list);
}
}
方法二:迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null) return ans;
Deque<TreeNode> stack = new LinkedList<>();
TreeNode node = root;
//遍历终止条件:当前节点为空并且栈为空
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
ans.add(node.val);
//找到最左边的节点
node = node.left;
}
node = stack.pop();
node = node.right;
}
return ans;
}
}