首页 > 其他 > 详细

LeetCode | Construct Binary Tree from Preorder and Inorder Traversal

时间:2014-03-29 02:37:32      阅读:412      评论:0      收藏:0      [点我收藏+]

题目

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

分析

确定中序遍历中根节点位置,递归构造左右子树

代码

public class ConstructBinaryTreeFromPreorderAndInorderTraversal {
	public TreeNode buildTree(int[] preorder, int[] inorder) {
		return solve(preorder, 0, inorder, 0, inorder.length - 1);
	}

	private TreeNode solve(int[] preorder, int p, int[] inorder, int low,
			int high) {
		if (low > high) {
			return null;
		}
		TreeNode root = new TreeNode(preorder[p]);
		int cutPos = 0;
		for (int i = low; i <= high; ++i) {
			if (preorder[p] == inorder[i]) {
				cutPos = i;
				break;
			}
		}
		root.left = solve(preorder, p + 1, inorder, low, cutPos - 1);
		root.right = solve(preorder, p + cutPos - low + 1, inorder, cutPos + 1,
				high);
		return root;
	}
}

LeetCode | Construct Binary Tree from Preorder and Inorder Traversal,布布扣,bubuko.com

LeetCode | Construct Binary Tree from Preorder and Inorder Traversal

原文:http://blog.csdn.net/perfect8886/article/details/22427675

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