Flatten Binary Tree to Linked List

题目描述

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

For example, Given

         1
        / \
       2   5
      / \   \
     3   4   6

The flattened tree should look like:

   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6

Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

解题方法

解法1:preorder traversal

从题目的例子马上发现其实就是preorder transverse整个tree,然后根据这个访问顺序,后访问到的节点成为先访问到的节点的右子节点。那么最不动脑的方法就是preorder transverse的时候把整个节点序列保存在一个vector中。最后再依次连起来。这个解法的空间复杂度包括了递归深度O(log n)和vector的空间O(n),所以总的空间复杂度是O(n)。

解法2

  • store the right child (we call R)

  • find the right-most node of left child

  • set R as the right-most node's right child.

  • set left child as the right child

  • set the left child NULL

  • set current node to current node's right child.

  • iterate these steps until all node are flattened.

Solution

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

class Solution(object):
    def flatten(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.
        """
        if not root:
            return
        left = root.left
        right = root.right
        if left:
            root.right = left
            root.left = None
            leftRight = left
            while leftRight.right:
                leftRight = leftRight.right
            leftRight.right = right

        self.flatten(root.right)

Reference