DFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new LinkedList<>();
recur(list, root);
return list; }
private void recur(List<Integer> list, TreeNode node) { if (node == null) { return; }
list.add(node.val); recur(list, node.left); recur(list, node.right); } }
|
Iterate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> resultList = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>(); if (root != null) { stack.push(root); }
while (!stack.isEmpty()) { TreeNode node = stack.pop(); resultList.add(node.val);
if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } }
return resultList; } }
|
Iterate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> resultList = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>(); while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); resultList.add(root.val); root = root.left; }
TreeNode node = stack.pop(); if (node.right != null) { root = node.right; } }
return resultList; } }
|
References
144. Binary Tree Preorder Traversal