代码改变世界

Morris Traversal_ O(1) space to change binary tree to linked list

2021-06-18 19:04  Johnson_强生仔仔  阅读(46)  评论(0编辑  收藏  举报

问题可以参考[LeetCode] 114. Flatten Binary Tree to Linked List_Medium tag: DFS, 这个Morris Traversal能够解决follow up,怎么样用 space O(1) 来去解决这个问题。参考这个题目的solution的approach3. 利用比较greedy的方式一步一步去iterative,很腻害。

1. 判断root是否有 left, 如果有,那就把left tree 的rightmost child 找到,注意这个rightmost node的right肯定是None, 然后将root.right 放到这个node的right, 实际上就是相当于暂时把这个root.right 存到了这个rightmost node的right.

步骤结束之后,就把root.left, root.right = None, root.left

 

2. 第一步结束之后就如下图所示

 

3. 把root = root.right, 再重复步骤1, 直到root 成为None

 

 T: O(n),    S: O(1)!!!

 

def flatten(self, root: 'TreeNode') -> None:
    if not root: return
    while root:
        if root.left:
            rightMost = root.left
            # find the rightMost node
            while rightMost.right:
                rightMost = rightMost.right
            # save root.right into rightMost.right, remember rightMost.right = None
            rightMost.right = root.right
            root.right = root.left
            root.left = None
        # continue the iteration
        root = root.right