LeetCode 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

/**
 * 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;
            }
            if (root.left==null) {
                flatten(root.right);
                return;
            }

            TreeNode lefTreeNode=root.left;

            TreeNode righTreeNode=root.right;
            if (righTreeNode==null) {
                flatten(lefTreeNode);
                root.left=null;
                root.right=lefTreeNode;
                return;
            }
            if (lefTreeNode.left==null && 
                    lefTreeNode.right==null&& 
                    righTreeNode.right==null && 
                    righTreeNode.left==null) {
                root.left=null;
                root.right=lefTreeNode;
                lefTreeNode.right=righTreeNode;
                return;
                
            }
            
            flatten(lefTreeNode);
            flatten(righTreeNode);
            root.left=null;
            root.right=lefTreeNode;
            lefTreeNode.left=null;
            TreeNode node=lefTreeNode;
            while (node.right!=null) {
                node=node.right;
            }
            node.right=righTreeNode;
            return;
            
        
    }
}

 

posted @ 2014-10-30 23:34  birdhack  阅读(142)  评论(0编辑  收藏  举报