Flatten Binary Tree to Linked List
同理,这题递归的解法trivial,试着用iterative解了下,后续遍历,然后找左子树的右孩子。然后…就不需要然后了
# 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.
"""
if not root: return
stk = [root]
pre = None
while stk:
cur = stk[-1]
if not pre or pre.left==cur or pre.right==cur:
if cur.left:
stk.append(cur.left)
elif cur.right:
stk.append(cur.right)
elif cur.left==pre:
if cur.right:
stk.append(cur.right)
else:
stk.pop()
if cur.left:
curl = cur.left
while curl.right:
curl = curl.right
curl.right = cur.right
cur.right = cur.left
cur.left = None
pre = cur