Tree traversal: In-order traversal non-recursion

如果有一棵樹 [1, 2, 3, 4, 5, 6] 要做 inorder traversal non-resursion

虛擬算法如下:

  1. initialize a stack and push root into it.
  2. initialize a cur TreeNode and set its value to root.
  3. push all cur's left children into stack if any.
  4. pop a element from stack and print it.
  5. if the element has right, push it into stack and go back to 3.
public void inorderTraversal(TreeNode root) {
    if (root == null) {
        return;
    }

    Stack<TreeNode> S = new Stack<TreeNode>();  //1
    TreeNode cur;  //2
    while (true) {  
        while (cur != null) {  //3
            S.push(cur);
            cur = cur.left;
        }

        if (S.isEmpty()) {
            break;
        }

        cur = S.pop(); //4
        System.out.print(node.val);

        cur = cur.right; //5
    }
    return;
}

results matching ""

    No results matching ""