码迷,mamicode.com
首页 > 其他好文 > 详细

Flatten Binary Tree to Linked List

时间:2015-04-07 09:58:30      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:leecode   树操作   

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
Given a binary tree, flatten it to a linked list in-place.

题目很简单,就是将一棵树化成一棵右单支树,过程是:将节点的作节点接到右节点的位置,原来的右节点接到现在右节点(也就是左节点)的最右节点的右子树,重复这个过程,直到是一棵右单支树。

/**
 * 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 p = root;
        TreeNode left = null;
        TreeNode right = null;
        TreeNode q = null;
        while(p != null ){//空节点退出
             left = p.left;
             right = p.right;
             if(left != null){//左子树不空,需要知道左子树的最右节点
                 q = ButtomRight(left);
                 p.left = null;
                 p.right = left;
                 q.right = right;
                 p = p.right;
             }else{//左子树为空
                 p = p.right; 
             }
        }
    }
    public TreeNode ButtomRight(TreeNode root){//返回root的最右节点
        TreeNode tmp = root;
        while(root.right != null){
            tmp = root.right;
            root = root.right;
        }
        return tmp;
    }
}


Flatten Binary Tree to Linked List

标签:leecode   树操作   

原文地址:http://blog.csdn.net/havedream_one/article/details/44905591

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!