卖萌的弱渣

I am stupid, I am hungry.

Flatten Binary Tree to Linked List

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

Example

Given

1
2
3
4
5
     1
    / \
   2   5
  / \   \
 3   4   6

The flattened tree should look like:

1
2
3
4
5
6
7
8
9
10
11
   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.

Solution

  • Java Solution
(Flatten-Binary-Tree-to-Linked-List.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode prev = null;
    public void flatten(TreeNode root) {
        if(root==null)
            return ;
        flatten(root.right);
        flatten(root.left);
        root.right = prev;
        root.left = null;
        prev = root;
    }
}
  • Python Solution
  • Pre-order and put node into a stack.
  • change the tree by the nodes in stack.
(Flatten-Binary-Tree-to-Linked-List.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 # 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 root

        stack = []
        node = root
        # pre-order tranversal
        self.pre_order(stack,root)

        stack.pop(0)
        # change tree
        while stack:
            node.right = stack.pop(0)
            node.left = None
            node = node.right


    def pre_order(self,stack,root):
        if root == None:
            return
        stack.append(root)
        self.pre_order(stack,root.left)
        self.pre_order(stack,root.right)