Merge pull request #95 from Joshua-Lu/patch-11

更新 0106.从中序与后序遍历序列构造二叉树 Java版本
This commit is contained in:
Carl Sun
2021-05-14 10:12:17 +08:00
committed by GitHub

View File

@ -585,46 +585,38 @@ Java
```java ```java
class Solution { class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) { public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length == 0 || postorder.length == 0) return null; return buildTree1(inorder, 0, inorder.length, postorder, 0, postorder.length);
return buildTree(inorder, postorder,0,inorder.length,0,postorder.length);
} }
public TreeNode buildTree1(int[] inorder, int inLeft, int inRight,
private TreeNode buildTree(int[] inorder, int[] postorder, int infrom, int into, int[] postorder, int postLeft, int postRight) {
int postfrom, int postto) { // 没有元素了
if (postfrom == postto) return null; if (inRight - inLeft < 1) {
return null;
int rootValue = postorder[postto - 1]; }
TreeNode root = new TreeNode(rootValue); // 只有一个元素了
if (inRight - inLeft == 1) {
if (postfrom + 1 == postto) return root; return new TreeNode(inorder[inLeft]);
}
int splitNum = postto - 1; // 后序数组postorder里最后一个即为根结点
for (int i = infrom; i < into; i++) { int rootVal = postorder[postRight - 1];
if (inorder[i] == rootValue) { TreeNode root = new TreeNode(rootVal);
splitNum = i; int rootIndex = 0;
break; // 根据根结点的值找到该值在中序数组inorder里的位置
for (int i = inLeft; i < inRight; i++) {
if (inorder[i] == rootVal) {
rootIndex = i;
} }
} }
// 根据rootIndex划分左右子树
int inLeftBegin = infrom; root.left = buildTree1(inorder, inLeft, rootIndex,
int inLeftEnd = splitNum; postorder, postLeft, postLeft + (rootIndex - inLeft));
int inRightBegin = splitNum + 1; root.right = buildTree1(inorder, rootIndex + 1, inRight,
int inRightEnd = into; postorder, postLeft + (rootIndex - inLeft), postRight - 1);
int postLeftBegin = postfrom;
int postLeftEnd = postLeftBegin + (splitNum - inLeftBegin);
int postRightBegin = postLeftBegin + (splitNum - inLeftBegin);
int postRightEnd = postto - 1;
root.left = buildTree(inorder,postorder,inLeftBegin,inLeftEnd,postLeftBegin,postLeftEnd);
root.right = buildTree(inorder,postorder,inRightBegin,inRightEnd,postRightBegin,postRightEnd);
return root; return root;
} }
} }
``` ```
Python Python