Leetcode 114, Flatten Binary Tree to Linked List
Posted lettuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 114, Flatten Binary Tree to Linked List相关的知识,希望对你有一定的参考价值。
根据提示,本题等价于pre order traverse遍历,并且依次把所有的节点都存成right child,并把left child定义成空集。用递归的思想,那么如果分别把左右子树flatten成list,我们有:
1
/ \
2 5
\ \
3 6 <- rightTail
\
4 <- leftTail
所以使用递归的解法一: 注意由于右子树最后要接到左子树的后面,所以用temp保存右子树的head。
1 def flatten(self, root): 2 """ 3 :type root: TreeNode 4 :rtype: void Do not return anything, modify root in-place instead. 5 """ 6 if not root: 7 return 8 self.flatten(root.left) 9 self.flatten(root.right) 10 11 temp = root.right 12 13 root.right = root.left 14 root.left = None 15 16 while root.right: 17 root = root.right 18 19 root.right = temp
以上是关于Leetcode 114, Flatten Binary Tree to Linked List的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 114. Flatten Binary Tree to Linked List
leetcode--114. Flatten Binary Tree to Linked List
LeetCode 114. Flatten Binary Tree to Linked List
Leetcode 114, Flatten Binary Tree to Linked List