Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:

Given binary tree {1,#,2,3},

  1. 1
  2. \
  3. 2
  4. /
  5. 3

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<Integer> preorderTraversal(TreeNode root) {
  12. List<Integer> res = new ArrayList<Integer>();
  13. if (root == null)
  14. return res;
  15. Stack<TreeNode> stack = new Stack<TreeNode>();
  16. stack.push(root);
  17. while (!stack.isEmpty()) {
  18. TreeNode node = stack.pop();
  19. res.add(node.val);
  20. if (node.right != null)
  21. stack.push(node.right);
  22. if (node.left != null)
  23. stack.push(node.left);
  24. }
  25. return res;
  26. }
  27. }