zoukankan      html  css  js  c++  java
  • 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)
    

      

  • 相关阅读:
    springboot+https+http
    3.kettle-定时执行任务
    sqlserver清空删除日志
    C++学习(二)
    随笔(二) 安装Code::Blocks遇到的问题
    随笔(一) tensorflow环境的搭建
    C++学习(一)
    前端学习日记 (三)
    前端学习日记 (二)
    前端学习日记 (一)
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12954890.html
Copyright © 2011-2022 走看看