题目
思路
用一个lastnode记录上一个节点,然后遍历左子树和右子树。
右子树节点需要先取出,因为root结构会改变,递归回到栈的位置时,取不到right。
代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: a TreeNode, the root of the binary tree
@return:
"""
def __init__(self):
self.lastnode = None
def flatexec(self, root):
if not root:
return None
rightnode = root.right
if not self.lastnode:
self.lastnode = root
else:
self.lastnode.right = root
self.lastnode.left = None
self.lastnode = root
self.flatexec(root.left)
self.flatexec(rightnode)
def flatten(self, root):
# write your code here
self.flatexec(root)