Can you do Iterative Pre-oprder Traversal of a Binary Tree without Recursion?

Technology CommunityCategory: Binary TreeCan you do Iterative Pre-oprder Traversal of a Binary Tree without Recursion?
VietMX Staff asked 3 years ago

Given a binary tree, return the preorder traversal of its nodes’ values. Can you do it without recursion?

Let’s use Stack:

  1. Set current node as root
  2. Check if current node is null then return
  3. Store current node value in the container
  4. Put right on stack
  5. Put left on stack
  6. While stack is not empty
    1. pop from stack into current node. Note, the left will be on top of stack, and will be taken first
    2. Repeat from step 2
Implementation
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
public List<Integer> preorderTraversal(TreeNode root) {
  if (root == null) {
    return new ArrayList<>();
  }

  List<Integer> rst = new ArrayList<>();
  Stack<TreeNode> stack = new Stack<>();
  stack.push(root);

  while (!stack.empty()) {
    TreeNode node = stack.pop();
    rst.add(node.val);
    if (node.right != null) {
      stack.push(node.right);
    }
    if (node.left != null) {
      stack.push(node.left);
    }
  }

  return rst;
}