Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
思路:递归构造,因为后序遍历中最后一个节点是根节点,因此类似于先序遍历,根据后序根节点将中序分为左右两部分,递归构建左右子树。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode build(int[] inorder,int inLeft,int inRight,int[] postorder,int postLeft, int postRight){ if(inLeft > inRight ||postLeft > postRight) return null; TreeNode n = new TreeNode(postorder[postRight]); int roorIndex = -1; for(int i = inLeft; i <= inRight; i++){ if(inorder[i] == postorder[postRight]){ roorIndex = i; break; } } int lLen = roorIndex - inLeft; int RLen = inRight - roorIndex; n.right = build(inorder,roorIndex + 1,inRight,postorder,postRight - RLen,postRight - 1); n.left = build(inorder,inLeft,roorIndex - 1,postorder,postLeft,postLeft + lLen - 1); return n; } public TreeNode buildTree(int[] inorder, int[] postorder) { return build(inorder,0,inorder.length - 1,postorder,0,postorder.length - 1); } }