Flatten Binary Tree to Linked List - LeetCode
题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
分析:
我们观察这个转化,可以发现其实就是一个先序遍历的顺序,这样就好做了,但是一开始的时候我在如何在root本身上加右子节点也是考虑很久,此方法在root node上直接操作,先暂时保存左右子树,如果root有左子树,把root.right附城root.left,root.left归null,再在已经是右子树的左子树上找rightmost 的node,把之前存住的right子树放在rightmost.right上即可。做完一遍以后,这时root的左子树已经已经被嫁接到了右子树和root之间,原来的左子树变成null,可以进行root.right的递归了。这个方法我也是看别人博客上来的,在这个地址方面的控制绕了好久。。。
代码:
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
if not root:
return None
left = root.left
right = root.right
if left != None:
root.right = left
root.left = None
rightmost = left
while rightmost.right != None:
rightmost = rightmost.right
rightmost.right = right
self.flatten(root.right)