Leetcode练习(Python):树类:第114题:二叉树展开为链表:给定一个二叉树,原地将它展开为一个单链表。

题目:

二叉树展开为链表:给定一个二叉树,原地将它展开为一个单链表。

例如,给定二叉树

1
/
2 5
/
3 4 6
将其展开为:

1

2

3

4

5

6

思路:

先使用前序遍历,再按顺序构建一个没有左子树的树。

程序:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def flatten(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        if not root:
            return root
        self.auxiliary = []
        self.preorder(root)
        index = 1
        root.left = None
        node = root
        while index < len(self.auxiliary):
            node.right = TreeNode(self.auxiliary[index])
            node = node.right
            index += 1

    def preorder(self, root):
        if not root:
            return 
        self.auxiliary.append(root.val)
        self.preorder(root.left)
        self.preorder(root.right)

  

原文地址:https://www.cnblogs.com/zhuozige/p/12954890.html