题目
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
TreeNode root = helper(inorder,0,inorder.length-1,postorder,0,inorder.length-1);
return root;
}
public TreeNode helper(int[] inorder, int inLeft,int inRight, int[] postorder,int postLeft,int postRight){
if(inLeft > inRight || postLeft > postRight){
return null;
}
int pivot = postorder[postRight];
TreeNode root = new TreeNode(pivot);
int pivotIndex = inLeft;
while(inorder[pivotIndex] != pivot){
pivotIndex++;
}
root.left = helper(inorder,inLeft,pivotIndex-1,postorder,postLeft,postLeft+(pivotIndex-1-inLeft));
root.right = helper(inorder,pivotIndex+1,inRight,postorder,postLeft+(pivotIndex-inLeft),postRight-1);
return root;
}
}
从中序和前序遍历构造二叉树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return helper(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode helper(int[] preorder,int preLeft,int preRight,int[] inorder,int inLeft, int inRight){
if(preLeft > preRight || inLeft > inRight){
return null;
}
int pivot = preorder[preLeft];
TreeNode root = new TreeNode(pivot);
int pivotIndex = inLeft;
while(inorder[pivotIndex] != pivot){
pivotIndex++;
}
root.left = helper(preorder,preLeft+1,preLeft+(pivotIndex-inLeft),inorder,inLeft,pivotIndex-1);
root.right = helper(preorder,preLeft+(pivotIndex-inLeft)+1,preRight,inorder,pivotIndex+1,inRight);
return root;
}
}