首页 > 其他 > 详细

Flatten Binary Tree to Linked List

时间:2015-04-07 09:56:44      阅读:140      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!