这题要求就是在原有的基础上修改。将原来的tree修改成按照前序遍历的格式。采用的方法是先用一个栈存起来顺序,然后依次改变。代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
stack = []
def preorder(root):
if not root:
return root
stack.append(root)
if root.left:
preorder(root.left)
if root.right:
preorder(root.right)
return stack
preorder(root)
if not root:
return root
for i in range(len(stack) - 1):
stack[i].left = None
stack[i].right = stack[i + 1]