[Tree]114. Flatten Binary Tree to Linked List

  • 分类:Tree
  • 时间复杂度: O(n) 这种把树的节点都遍历一遍的情况时间复杂度为O(n)
  • 空间复杂度: O(1)

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    
    prev=None
    
    def flatten(self, root: 'TreeNode') -> 'None':
        """
        Do not return anything, modify root in-place instead.
        """
        if root==None:
            return

        self.flatten(root.right)
        self.flatten(root.left)
        
        root.right=self.prev
        root.left=None
        self.prev=root

讨论:

1.这道题也是一道一开始以为很难不会做,结果看了讲解发现很简单的题
2.这道题的讲解看的是公瑾讲解
3.主要的思想是保存的值放到Node的右边,再进行左子树的清零,再把prev进行更新
4.也考察了后序遍历的特点

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容