[leedcode 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
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        //左节点赋值到右节点,右节点变成原左节点的最右边节点的右节点
/*        (1) 找到左节点最右的子节点
        (2) 保存右节点
        (3) 将原左节点放到右节点
        (4) 左节点置空
        (5) 原右节点变成原左节点的最右节点
        (6) 向下遍历,直到空节点*/
        if(root==null) return;
        TreeNode node=root;
       while(node!=null){
            if(node.left!=null){
            TreeNode right=node.left;
            while(right.right!=null){
                right=right.right;
            }
            TreeNode temp=node.right;
            node.right=node.left;
            node.left=null;
            right.right=temp;
            
            }
            node=node.right;
       }
    }
}

 

posted @ 2015-07-22 20:11  ~每天进步一点点~  阅读(114)  评论(0编辑  收藏  举报