mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0106.从中序与后序遍历序列构造二叉树.md
新增一java寫法 和卡哥的思路一樣的
This commit is contained in:
@ -622,7 +622,42 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
public TreeNode buildTree(int[] inorder, int[] postorder) {
|
||||||
|
if(postorder.length == 0 || inorder.length == 0)
|
||||||
|
return null;
|
||||||
|
return buildHelper(inorder, 0, inorder.length, postorder, 0, postorder.length);
|
||||||
|
|
||||||
|
}
|
||||||
|
private TreeNode buildHelper(int[] inorder, int inorderStart, int inorderEnd, int[] postorder, int postorderStart, int postorderEnd){
|
||||||
|
if(postorderStart == postorderEnd)
|
||||||
|
return null;
|
||||||
|
int rootVal = postorder[postorderEnd - 1];
|
||||||
|
TreeNode root = new TreeNode(rootVal);
|
||||||
|
int middleIndex;
|
||||||
|
for (middleIndex = inorderStart; middleIndex < inorderEnd; middleIndex++){
|
||||||
|
if(inorder[middleIndex] == rootVal)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
int leftInorderStart = inorderStart;
|
||||||
|
int leftInorderEnd = middleIndex;
|
||||||
|
int rightInorderStart = middleIndex + 1;
|
||||||
|
int rightInorderEnd = inorderEnd;
|
||||||
|
|
||||||
|
|
||||||
|
int leftPostorderStart = postorderStart;
|
||||||
|
int leftPostorderEnd = postorderStart + (middleIndex - inorderStart);
|
||||||
|
int rightPostorderStart = leftPostorderEnd;
|
||||||
|
int rightPostorderEnd = postorderEnd - 1;
|
||||||
|
root.left = buildHelper(inorder, leftInorderStart, leftInorderEnd, postorder, leftPostorderStart, leftPostorderEnd);
|
||||||
|
root.right = buildHelper(inorder, rightInorderStart, rightInorderEnd, postorder, rightPostorderStart, rightPostorderEnd);
|
||||||
|
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
105.从前序与中序遍历序列构造二叉树
|
105.从前序与中序遍历序列构造二叉树
|
||||||
|
|
||||||
```java
|
```java
|
||||||
|
Reference in New Issue
Block a user