Search code examples
javaalgorithmrecursiontraversalbinary-tree

How do I iterate over Binary Tree?


Right now I have

 private static void iterateall(BinaryTree foo) {
    if(foo!= null){
    System.out.println(foo.node);
    iterateall(foo.left);
    iterateall(foo.right);
   }
  }

Can you change it to Iteration instead of a recursion?


Solution

  • Can you change it to Iteration instead of a recursion?

    You can, using an explicit stack. Pseudocode:

    private static void iterateall(BinaryTree foo) {
        Stack<BinaryTree> nodes = new Stack<BinaryTree>();
        nodes.push(foo);
        while (!nodes.isEmpty()) {
            BinaryTree node = nodes.pop();
            if (node == null)
                continue;
            System.out.println(node.node);
            nodes.push(node.right);
            nodes.push(node.left);
        }
    }
    

    But this isn’t really superior to the recursive code (except for the missing base condition in your code).