Iterative way to solve preorder/inorder/postorder traverse of tree

Here I summarize the iterative implementation for preorder, inorder, and postorder traverse.


Pre Order Traverse


public List preorderTraversal(TreeNode root) {
    List result = new ArrayList<>();
    Deque stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            result.add(p.val);  // Add before going to children
            p = p.left;
        } else {
            TreeNode node = stack.pop();
            p = node.right;   
        }
    }
    return result;
}


In Order Traverse


public List inorderTraversal(TreeNode root) {
    List result = new ArrayList<>();
    Deque stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            p = p.left;
        } else {
            TreeNode node = stack.pop();
            result.add(node.val);  // Add after all left children
            p = node.right;   
        }
    }
    return result;
}


Post Order Traverse


public List postorderTraversal(TreeNode root) {
    LinkedList result = new LinkedList<>();
    Deque stack = new ArrayDeque<>();
    TreeNode p = root;
    while(!stack.isEmpty() || p != null) {
        if(p != null) {
            stack.push(p);
            result.addFirst(p.val);  // Reverse the process of preorder
            p = p.right;             // Reverse the process of preorder
        } else {
            TreeNode node = stack.pop();
            p = node.left;           // Reverse the process of preorder
        }
    }
    return result;
}

你可能感兴趣的:(Iterative way to solve preorder/inorder/postorder traverse of tree)