1. 程式人生 > 其它 >Morris Traversal_ O(1) space to change binary tree to linked list

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

問題可以參考[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