标签:
Given inorder and postorder traversal of a tree, construct the binary tree.
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** *@param inorder : A list of integers that inorder traversal of a tree *@param postorder : A list of integers that postorder traversal of a tree *@return : Root of a tree */ public TreeNode buildTree(int[] inorder, int[] postorder) { // write your code here if(inorder == null || inorder.length == 0) return null; int size = inorder.length; TreeNode root = build(inorder, 0, size - 1, postorder, 0, size - 1); return root; } public TreeNode build(int[] inorder, int in_start, int in_end, int[] postorder, int post_start, int post_end){ if(in_start > in_end || post_start > post_end) return null; TreeNode root = new TreeNode(postorder[post_end]); int k = in_start; for(; k < in_end; k++){ if(inorder[k] == postorder[post_end]) break; } TreeNode left = build(inorder, in_start, k - 1, postorder, post_start, post_start + k - 1 - in_start); TreeNode right = build(inorder, k + 1, in_end, postorder, post_start + k - in_start, post_end - 1); root.left = left; root.right = right; return root; } }
lintcode-medium-Construct Binary Tree from Inorder and Postorder Traversal
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5282824.html