根据后序集合找到根,再根据根,在中序集合中找到索引号,采用递归的构建子树的方法
/** * Definition for binary tree * 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 gT(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1); } private TreeNode gT(int[] inorder, int inStart, int inEnd, int[] postorder, int pStart, int pEnd){ if(inorder==null || postorder==null || inorder.length==0 || postorder.length==0 || inStart>inEnd || pStart>pEnd){ return null; } int childRootVal = postorder[pEnd]; TreeNode childRoot = new TreeNode(childRootVal); int childRootInOrderIndex = -1; for(int i=inStart; i<=inEnd; i++){ if(inorder[i]==childRootVal){ childRootInOrderIndex=i; break; } } if(childRootInOrderIndex==-1){ return null; } int duration = childRootInOrderIndex-inStart; childRoot.left=gT(inorder, inStart, childRootInOrderIndex - 1, postorder, pStart, pStart + duration - 1); childRoot.right=gT(inorder, childRootInOrderIndex+1,inEnd, postorder, pStart+duration, pEnd-1); return childRoot; } }
相关推荐
Javascript 的解决方案Leetcode Problems and interview problems in Javascript10 Regular Expresion Matching.js100 Same Tree.js101 Symmetric Tree.js102 Binary Tree Level Order Traversal.js103 Binary Tree ...
lru缓存leetcode LeetCode_Note leetcode 个人笔记 ...[106_construct-binary-tree-from-inorder-and-postorder-traversal.cpp] [107_binary-tree-level-order-traversal-ii.cpp] [108_convert-sorted
106.construct-binary-tree-from-inorder-and-postorder-traversal (从中序与后序遍历序列构造二叉树) 112.path-sum (路径总和) 116.populating-next-right-pointers-in-each-node (填充每个节点的下一个右侧节点
leetcode 跳跃 Algorithm 算法题解: 包括书籍算法, 程序员算法面试指南, 还有leetcode算法题 ...construct-binary-tree-from-inorder-and-postorder-traversal 无官方题解 116 populating-next-right-pointers-in-eac
201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _...