`
hcx2013
  • 浏览: 88912 次
社区版块
存档分类
最新评论

Construct Binary Tree from Inorder and Postorder Traversal

 
阅读更多

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

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	public TreeNode buildTree(int[] inorder, int[] postorder) {
    	return buildTree(inorder, 0, inorder.length, postorder, 0, postorder.length);
    }

	private TreeNode buildTree(int[] inorder, int i, int length,
			int[] postorder, int j, int length2) {
		if (i>length-1 || j>length2-1) {
			return null;
		}
		int tmp = postorder[length2-1];
		int index = 0;
		for (int k = i; k < length; k++) {
			if (inorder[k] == tmp) {
				index = k;
				break;
			}
		}
		int len = index-i;
		TreeNode root = new TreeNode(tmp);
		root.left = buildTree(inorder, i, index, postorder, j, j+len);
		root.right = buildTree(inorder, index+1, length, postorder, j+len, length2-1);
		return root;
	}
}

 

0
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics