[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.也考察了后序遍历的特点

你可能感兴趣的:([Tree]114. Flatten Binary Tree to Linked List)