114. 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

click to show hints.

---

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        
        if (root == null) return;

        TreeNode left = root.left;
        TreeNode right = root.right;
    
        if(left!=null){ // put to right
            root.right = left;
            root.left = null;
    
            TreeNode rightmost = left;
            while(rightmost.right != null){
                rightmost = rightmost.right;
            }
            rightmost.right = right; // point the right most to the original right child
        }
    
        flatten(root.right);        
    }
}

 

posted @ 2013-09-23 04:17  LEDYC  阅读(143)  评论(0)    收藏  举报