首页 > 其他 > 详细

leetcode------Flatten Binary Tree to Linked List

时间:2015-03-12 23:52:08      阅读:293      评论:0      收藏:0      [点我收藏+]
标题: Flatten Binary Tree to Linked List
通过率: 28.7%
难度: 中等

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.

Hints:

If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.

本题就是把一颗树变成退化树

都是只有右孩子,那么需要操作的就是找到左孩子的最有节点,将root的右树连接到左孩子的最右节点,然后root的右孩子指向左孩子,root的左孩子置空

 

看代码具体操作:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public void flatten(TreeNode root) {
12        while(root!=null){
13            if(root.left!=null){
14             TreeNode tmp=root.left;
15             while(tmp.right!=null)
16                 tmp=tmp.right;
17             tmp.right=root.right;
18             root.right=root.left;
19             root.left=null;
20            }
21             root=root.right;
22        }
23     }
24 }

 

leetcode------Flatten Binary Tree to Linked List

原文:http://www.cnblogs.com/pkuYang/p/4333946.html

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