Friday, February 7, 2014

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

Solution:
The result seems like a pre-order traverse, how can we align tree nodes that way? We can use a class variable to point to its previous node, and let the root be the right child of the previous node, and then update the previous node. 


public class Solution {
    TreeNode prev = new TreeNode(0);
    public void flatten(TreeNode root) {
        if(root == null) return;
        prev.right = root;
        prev.left = null;
        prev = root;
        TreeNode rightSubTree = root.right;
        flatten(root.left);
        flatten(rightSubTree);
    }
}

No comments:

Post a Comment