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

【LeetCode】Flatten Binary Tree to Linked List

时间:2015-03-29 00:38:37      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:二叉树   单链表   leetcode   

题目:Flatten Binary Tree to Linked List

<span style="font-size:18px;">/**LeetCode Flatten Binary Tree to Linked List
 * 题意:给定一个二叉树,将其转变为一个相当于单链表的结构,观察可知该结构即:每一个节点左儿子为空,右儿子指向自己先序遍历时的下一个节点
 * 思路:有观察可得,应对其进行先序遍历,得到正确的序列连接起来
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */ 
package javaTrain;

public class Train18 {
	public void flatten(TreeNode root) {
		if(root== null || (root.left == null && root.right == null)) return;
		preOrder(root);
		return;
    }
	private TreeNode preOrder(TreeNode root){
		if(root== null || (root.left == null && root.right == null)) return root;
		TreeNode left = root.left;
		TreeNode right = root.right;
		TreeNode last;
		root.left = null; 
		if(left != null){
			root.right = left;
			last = preOrder(left);
			last.left = null;
			if(right != null){
				last.right = right;
				return preOrder(right);
			}
			else return last;
		}
		else{
			root.right = right;
			return preOrder(right);
		}
	}
}
</span>


【LeetCode】Flatten Binary Tree to Linked List

标签:二叉树   单链表   leetcode   

原文地址:http://blog.csdn.net/ymzmdx/article/details/44710533

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