将二叉树拆成链表
中文English
将一棵二叉树按照前序遍历拆解成为一个 假链表
。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
Example
样例 1:
输入:{1,2,5,3,4,#,6}
输出:{1,#,2,#,3,#,4,#,5,#,6}
解释:
1
/
2 5
/
3 4 6
1
2
3
4
5
6
样例 2:
输入:{1}
输出:{1}
解释:
1
1
Challenge
不使用额外的空间耗费。
Notice
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten(self, root): # write your code here if not root: return last_node = dummy = TreeNode(None) stack = [root] while stack: node = stack.pop() last_node.right = node if node.right: stack.append(node.right) if node.left: stack.append(node.left) node.left, node.right = None, None last_node = node
class Solution: last_node = None """ @param root: a TreeNode, the root of the binary tree @return: nothing """ def flatten(self, root): if root is None: return if self.last_node is not None: self.last_node.left = None self.last_node.right = root self.last_node = root right = root.right self.flatten(root.left) self.flatten(right)
后者是使用递归的解法。但是要注意变量修改的细节。
需要在遍历中记住上次遍历节点,根据上次的节点和当前节点进行比较而得到result的算法模板:
class Solution(): last_node = None result = None def run(self, root): self.dfs(root) return self.result def dfs(self): if last_node is None: last_node = root else: do_sth(last_node, root) dfs(root.left) dfs(root.right)