LeetCode 114. Flatten Binary Tree to Linked List(Python)

来源:互联网 发布:网络大v颠倒是非 编辑:程序博客网 时间:2024/05/22 03:08

题目描述:
Given a binary tree, flatten it to a linked list in-place.

For example,
Given

     1    / \   2   5  / \   \ 3   4   6

The flattened tree should look like:

1 \  2   \    3     \      4       \        5         \          6

思路:
用列表保存该二叉树的前序遍历的结点,最后循环列表重新赋左右子树。

AC代码:

class Solution(object):    def flatten(self, root):        """        :type root: TreeNode        :rtype: void Do not return anything, modify root in-place instead.        """        ans = []        def preOrderTravel(root):            if not root:                return            ans.append(root)            preOrderTravel(root.left)            preOrderTravel(root.right)        preOrderTravel(root)        copy = root        for i in range(1, len(ans)):            copy.left = None            copy.right = ans[i]            copy = ans[i]
原创粉丝点击