Summary of non-recursive in-order traversal of binary trees (2 methods)

Algorithm non-recursive in-order traversal of binary tree summary (2 methods)

@author:Jingdai
@date:2020.12.03

Portal

method 1

The first-order traversal is the first time the node is traversed; the middle-order is the second time the node is traversed; and the post-order is the third time the node is traversed. Non-recursive traversal using the stack, the first encounter is when the stack is pushed, and the second is when the stack is popped, so the middle order traversal should be traversed when the stack is popped. After popping the stack, it means that the popping stack node and its left subtree have been traversed, so at this time the right subnode of the popping stack node is pushed onto the stack, and the same operation is performed on its right subtree. code show as below.

public static void inOrderTraverse(TreeNode root) {
    
    

    TreeNode p = root;
    LinkedList<TreeNode> stack = new LinkedList<>();

    while (p != null || stack.size() != 0) {
    
    
        while (p != null) {
    
    
            stack.push(p);
            p = p.left;
        }
        p = stack.pop();
        System.out.println(p.val);
        p = p.right;
    }
}

In fact, if you carefully observe the code, you will find that in fact, except for the position of the traversal (here is the output statement), the middle order and the first order code are exactly the same, so the first order and the middle order will be one type, and the other will also be . ps: For the first preface, you can see the summary of my last article .

Method 2 Morris method

Morris is a method in order to traverse the spatial complexity from O(h)reduced O(1), if Morris traversal problem I can see the summary before a preorder traversal, here directly on the code.

public static void inOrderTraverse(TreeNode root) {
    
    

    TreeNode cur = root;
    TreeNode rightmost = null;

    while (cur != null) {
    
    
        if (cur.left != null) {
    
    
            rightmost = cur.left;
            while (rightmost.right != null && rightmost.right != cur) {
    
    
                rightmost = rightmost.right;
            }
            if (rightmost.right == null) {
    
     // first
                rightmost.right = cur;
                cur = cur.left;
            } else {
    
     // second
                rightmost.right = null;
                System.out.println(cur.val);
                cur = cur.right;
            }
        } else {
    
    
            System.out.println(cur.val);
            cur = cur.right;
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_41512783/article/details/110583191