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

Flatten Binary Tree to Linked List

时间:2015-11-09 22:38:44      阅读:237      评论: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
先对二叉树进行前序排列,然后放进一个只有右支树的二叉树中
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     /**
14      * @param root: a TreeNode, the root of the binary tree
15      * @return: nothing
16      */
17     public void flatten(TreeNode root) {
18         // write your code here
19         if (root == null)   return;  
20         TreeNode cur =  root , pre = null;
21         while(cur != null){  //当前节点不为空
22             if ( cur.left != null){  //当前节点有左儿子
23                 pre = cur.left;   
24                 while ( pre.right !=null ) pre = pre.right;  //当前节点的右儿子指向左儿子,左儿子的最右儿子指向当前节点的右儿子
25                 pre.right = cur.right;
26                 cur.right = cur.left;
27                 cur.left  = null;
28             }
29             cur=cur.right;
30         }
31     }
32 }

 

Flatten Binary Tree to Linked List

标签:

原文地址:http://www.cnblogs.com/wangnanabuaa/p/4951193.html

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