https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
思路和106. 从中序与后序遍历序列构造二叉树相同
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0 || inorder.length==0)return null;
return build(preorder,inorder,0,preorder.length,0,inorder.length);
}
// 左闭右开
public TreeNode build(int[] preorder,int[] inorder,int preStart,int preEnd,int inStart,int inEnd)
{
if(preStart==preEnd)return null;
TreeNode root = new TreeNode(preorder[preStart]);
int mid;
for(mid=inStart;mid<inEnd;mid++)
if(inorder[mid]==preorder[preStart])break;
int leftInStart = inStart;
int leftInEnd = mid;
int rightInStart = mid+1;
int rightInEnd = inEnd;
int leftPreStart = preStart+1;
// leftInEnd-leftInStart 是中序左子树长度
System.out.println(leftInEnd-leftInStart);
int leftPreEnd = leftPreStart + leftInEnd - leftInStart;
int rightPreStart = leftPreEnd;
int rightPreEnd = preEnd;
root.left = build(preorder,inorder,leftPreStart,leftPreEnd,leftInStart,leftInEnd);
root.right = build(preorder,inorder,rightPreStart,rightPreEnd,rightInStart,rightInEnd);
return root;
}
}
标签:preorder,right,TreeNode,val,int,inorder,二叉树,106,105 From: https://www.cnblogs.com/lxl-233/p/18173617