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

【LeetCode从零单排】No 114 Flatten Binary Tree to Linked List

时间:2015-03-16 16:33:35      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   

题目

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
解题思路:利用递归找到倒数第一个父节点,记录下它的右节点,将左边的移到右边,然后再把之前标记的右节点连接上。

代码

public class Solution {
    public void flatten(TreeNode root) {
        if(root==null) return;
        flatten(root.left);
        flatten(root.right);
        TreeNode temp=root.right;
        if(root.left!=null){
            root.right=root.left;
            root.left=null;
            
        
        while(root.right != null){
           root=root.right;
        }
        root.right=temp;
            
        }
        
    }
}




/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



【LeetCode从零单排】No 114 Flatten Binary Tree to Linked List

标签:leetcode   java   

原文地址:http://blog.csdn.net/buptgshengod/article/details/44306461

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