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

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

时间:2015-03-12 23:53:25      阅读:194      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!