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

LeetCode Flatten Binary Tree to Linked List

时间:2015-05-11 14:54:35      阅读:134      评论: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

click to show hints.

题意:将一个二叉搜索树整成递增链表。

思路:首先我们能想到先序遍历的过程,所以我们要想办法将左子树最大的节点连接上右子树。然后为了变成链表所以我们将左子树置null,在这之前要将左子树移到右子树这边,类推下去处理。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private void make(TreeNode root) {
		if (root.left == null) return;
		
		TreeNode tmp = root.left;
		while (tmp.right != null) 
			tmp = tmp.right;
		
		tmp.right = root.right;
		root.right = root.left;
		root.left = null;
	}
	
    public void flatten(TreeNode root) {
       if (root == null) return;
       
       TreeNode tmp = root;
       while (tmp.right != null || tmp.left != null) {
    	   make(tmp);
    	   tmp = tmp.right;
       }
    }
}



LeetCode Flatten Binary Tree to Linked List

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45643081

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