题目大意:根据中序和后序构建二叉树。
法一:与105类似,只是这里是根据后序来确定根节点。代码如下(耗时15ms):
1 public TreeNode buildTree(int[] inorder, int[] postorder) { 2 if(postorder.length == 0 || inorder.length == 0) { 3 return null; 4 } 5 return dfs(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1); 6 } 7 private TreeNode dfs(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR) { 8 TreeNode root = new TreeNode(postorder[postR]); 9 int rootIndex = inL; 10 while(inorder[rootIndex] != postorder[postR]) { 11 rootIndex++; 12 } 13 int leftLen = rootIndex - inL; 14 int rightLen = inR - rootIndex; 15 if(leftLen != 0) { 16 root.left = dfs(inorder, postorder, inL, rootIndex - 1, postL, postL + leftLen - 1); 17 } 18 else { 19 root.left = null; 20 } 21 if(rightLen != 0) { 22 root.right = dfs(inorder, postorder, rootIndex + 1, inR, postL + leftLen, postR - 1); 23 } 24 else { 25 root.right = null; 26 } 27 return root; 28 }