114 Flatten Binary Tree to Linked List [Python]

114 Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

将二叉树展开成链表

[[]D:\dataStructure\Leetcode\114.png]
(D:\dataStructure\Leetcode\114.png "114")

思路:将根节点与左子树相连,再与右子树相连。递归地在每个节点的左右孩子节点上,分别进行这样的操作。

代码

class Solution(object):
    def flatten(self, root):
        if root == None:
            return
        if root.left == None and root.right == None:
            return
        self.flatten(root.left)
        self.flatten(root.right)
        tmp = root.left
        root.right = root.left
        root.left = None
        while root.right:
            root = root.right
        root.right = tmp

猜你喜欢

转载自www.cnblogs.com/wyz-2020/p/12382307.html