the purpose of this question is to let you recover the memory about post order tranverse.
Just as the post order tranverse, to solve this problem,you have to solve the left subtree of the root and then the root. and make the last node of the left tree link to the right subtree and make the root link to the root to the left tree.
you can try with recursion.
but another way to solve this question is to use stack.
the principle of stack is last input first output.
so you have to put the right tree into the stack first and then the left tree.
while stack is not empty,you stack the right tree of the current node that pop out and then the left.and link the pre to the current node and change the current node.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root==None:
return root
stack=[]
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
pre=root
while len(stack)!=0:
cur=stack.pop()
pre.right=cur
pre.left=None
if cur.right!=None:
stack.append(cur.right)
if cur.left!=None:
stack.append(cur.left)
pre=cur
return root