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

Construct Binary Tree from Inorder and Postorder Traversal

时间:2014-06-07 14:50:37      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:leetcode      递归   java   

题目

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

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

方法

根据树的中序遍历和后序遍历,来恢复树,使用递归的思想。

	TreeNode getTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) {
		if (inStart >= inEnd) {
			return null;
		}
		int cur = postorder[postEnd - 1];
		TreeNode root = new TreeNode(cur);
		int i = 0;
		int j = inStart;
		while(inorder[j] != cur) {
			j++;
			i++;
		}
		
		
		root.left = getTree(inorder, inStart, inStart + i, postorder, postStart, postStart + i);
		root.right = getTree(inorder, inStart + i + 1, inEnd, postorder, postStart + i, postEnd - 1);
		
		return root;
	}
    public TreeNode buildTree(int[] inorder, int[] postorder) {
    	if (inorder == null) {
    		return null;
    	}
    	int len = inorder.length;
    	return getTree(inorder, 0, len, postorder, 0, len);
    }


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

Construct Binary Tree from Inorder and Postorder Traversal

标签:leetcode      递归   java   

原文地址:http://blog.csdn.net/u010378705/article/details/28607977

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