Explain Morris inorder tree traversal without using stacks or recursion

前端 未结 8 1115
别跟我提以往
别跟我提以往 2020-11-27 09:15

Can someone please help me understand the following Morris inorder tree traversal algorithm without using stacks or recursion ? I was trying to understand how it works, but

8条回答
  •  粉色の甜心
    2020-11-27 09:28

    public static void morrisInOrder(Node root) {
            Node cur = root;
            Node pre;
            while (cur!=null){
                if (cur.left==null){
                    System.out.println(cur.value);      
                    cur = cur.right; // move to next right node
                }
                else {  // has a left subtree
                    pre = cur.left;
                    while (pre.right!=null){  // find rightmost
                        pre = pre.right;
                    }
                    pre.right = cur;  // put cur after the pre node
                    Node temp = cur;  // store cur node
                    cur = cur.left;  // move cur to the top of the new tree
                    temp.left = null;   // original cur left be null, avoid infinite loops
                }        
            }
        }
    

    I think this code would be better to understand, just use a null to avoid infinite loops, don't have to use magic else. It can be easily modified to preorder.

提交回复
热议问题