给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1 / \ 2 5 / \ \ 3 4 6
将其展开为:
1 \ 2 \ 3 \ 4 \ 5 \ 6
思路:先找一个第三方变量保存右子树,将左子树连接到右子树的位置,左子树=None,把右子树连接到左子树的后面。
# 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):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if not root:
return
if not root.left and not root.right:
return
self.flatten(root.left) #先完成各个子树上的操作
self.flatten(root.right)
tmp=root.right
root.right=root.left #然后再对整棵树进行变换
root.left=None
while root.right:
root=root.right
root.right=tmp
执行用时: 72 ms, 在Flatten Binary Tree to Linked List的Python3提交中击败了36.47% 的用户