Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
与前一篇《Construct Binary Tree from Preorder and Inorder Traversal 》类似,找出规律进行递归求解。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { //java public TreeNode buildSubTree(int [] preorder, int pbegin, int pend, int [] inorder, int ibegin, int iend){ TreeNode root = null; if(pbegin > pend || ibegin > iend) return root; if(ibegin == iend){ TreeNode tmp = new TreeNode(inorder[iend]); root = tmp; return root; } int value = inorder[iend]; int pos = 0; for(int i = pbegin; i <=pend; i++){ if(value == preorder[i]){ pos = i; break; } } int lnum = pos - pbegin; int rnum = pend - pos; TreeNode ltreeNode = buildSubTree(preorder,pbegin,pos-1,inorder,ibegin,ibegin+lnum-1); TreeNode rTreeNode = buildSubTree(preorder, pos+1, pend, inorder, ibegin+lnum, iend-1); TreeNode tmp = new TreeNode(inorder[iend]); tmp.left = ltreeNode; tmp.right = rTreeNode; root = tmp; return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { TreeNode root = null; if(preorder.length == 0) return root; root = buildSubTree(preorder , 0 , preorder.length-1, inorder, 0, inorder.length-1); return root; } }
原文地址:http://blog.csdn.net/chenlei0630/article/details/41408623