题目描述:给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1 / \ 2 5 / \ \ 3 4 6将其展开为:
1 \ 2 \ 3 \ 4 \ 5 \ 6
解法1。递归,根据题意是前序遍历也就是根-左-右,所以抚平后应该是根-左-右,所以放到树的遍历中就是,把根的左给右,再把右接到左的右边就是下面。递归一直到最左叶子结点的再返回到其父节点,基础操作就是把左赋给右,再把右接到左的右下方
# 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
if root.left:
self.flatten(root.left)
if root.right:
self.flatten(root.right)
tmp = root.right
root.right = root.left
root.left = None
while root.right:
root = root.right
root.right = tmp
解法2。用循环,基本思路是一致的,先找左子树的最右边的节点,在此节点下接右子树,然后左子树覆盖右子树,逐个下去,直到把所有左边都抚平转移到右边。
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
cur = root
while cur:
if cur.left:
p = cur.left
while p.right:
p = p.right
p.right = cur.right
cur.right = cur.left
cur.left = None
cur = cur.right