zoukankan      html  css  js  c++  java
  • 【leetcode】114: 二叉树展开为链表

    题目如下:

    这个题目很有意思,就是我们可以先用先序遍历遍历整棵树,然后再重新进行原地修改,就可以了。代码如下:

    # 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.
            """
            cur=root
            def dfs(root,ls):
                if root==None:
                    return None
                ls.append(root.val) 
                dfs(root.left,ls)
    
                dfs(root.right,ls)
            ls=[]
            dfs(root,ls)
            for i in ls:
                print(i)
    
            i=0
            while i<len(ls):
    
                if i!=0:
                    root.right=TreeNode(ls[i])
                    root.left=None
                    root=root.right
                if i==0:
                    root.left==None
                i+=1

    这样就可以了,有一个坑就是在进行原地修改的时候,一定要记得讲root.left进行删除,令其=none,不然难以得到正确的结果

  • 相关阅读:
    海量的数据的处理
    leetcode(135)分发糖果
    leetcode(130)被围绕的区域
    排序算法
    leetcode(956)最高的广告牌
    kafka的配置
    kafka命令行
    leetcode(76)最小覆盖子串
    Vue开发全解
    idea eclipse 设置代理
  • 原文地址:https://www.cnblogs.com/geeksongs/p/15404500.html
Copyright © 2011-2022 走看看