首页 > 其他 > 详细

【LeetCode】Flatten Binary Tree to Linked List

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

题目: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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!