Explain Morris inorder tree traversal without using stacks or recursion

前端 未结 8 1134
别跟我提以往
别跟我提以往 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:17

    Python Solution Time Complexity : O(n) Space Complexity : O(1)

    Excellent Morris Inorder Traversal Explanation

    class Solution(object):
    def inorderTraversal(self, current):
        soln = []
        while(current is not None):    #This Means we have reached Right Most Node i.e end of LDR traversal
    
            if(current.left is not None):  #If Left Exists traverse Left First
                pre = current.left   #Goal is to find the node which will be just before the current node i.e predecessor of current node, let's say current is D in LDR goal is to find L here
                while(pre.right is not None and pre.right != current ): #Find predecesor here
                    pre = pre.right
                if(pre.right is None):  #In this case predecessor is found , now link this predecessor to current so that there is a path and current is not lost
                    pre.right = current
                    current = current.left
                else:                   #This means we have traverse all nodes left to current so in LDR traversal of L is done
                    soln.append(current.val) 
                    pre.right = None       #Remove the link tree restored to original here 
                    current = current.right
            else:               #In LDR  LD traversal is done move to R  
                soln.append(current.val)
                current = current.right
    
        return soln
    

提交回复
热议问题