首页 > 其他 > 详细

LeetCode | Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-03-02 16:10:51      阅读:449      评论:0      收藏:0      [点我收藏+]

题目

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

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

分析

找到根节点,递归构造即可

代码

public class ConstructBinaryTreeFromInorderAndPostorderTraversal {
	private int[] inorder;
	private int[] postorder;

	public TreeNode buildTree(int[] inorder, int[] postorder) {
		assert inorder != null && postorder != null;
		assert inorder.length == postorder.length;

		this.inorder = inorder;
		this.postorder = postorder;
		int N = inorder.length;
		return solve(0, N - 1, 0, N - 1);
	}

	private TreeNode solve(int lowOfInorder, int highOfInorder,
			int lowOfPostorder, int highOfPostorder) {
		if (lowOfInorder > highOfInorder) {
			return null;
		}
		TreeNode root = new TreeNode(postorder[highOfPostorder]);
		for (int i = lowOfInorder; i <= highOfInorder; ++i) {
			if (inorder[i] == postorder[highOfPostorder]) {
				root.left = solve(lowOfInorder, i - 1, lowOfPostorder,
						lowOfPostorder + i - 1 - lowOfInorder);
				root.right = solve(i + 1, highOfInorder, highOfPostorder
						- highOfInorder + i, highOfPostorder - 1);
				break;
			}
		}
		return root;
	}
}


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

LeetCode | Construct Binary Tree from Inorder and Postorder Traversal

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

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