【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,不然难以得到正确的结果

 

posted @ 2021-10-13 22:16  Geeksongs  阅读(17)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.