Leetcode105/106/654之构建二叉树例题
构建二叉树例题
Leetcode106-从中序与后序遍历序列构建二叉树
- 给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树
- 输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
- 输出:[3,9,20,null,null,15,7]
public TreeNode buildTree(int[] inorder, int[] postorder) {
return build(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
}
public TreeNode build(int[] inorder, int inLeft, int inRight,int[] postorder, int postLeft, int postRight) {
if(inRight-inLeft<0){//没有元素了
return null;
}
if(inRight-inLeft==0){//只有一个元素
return new TreeNode(inorder[inLeft]);
}
//多个元素
int rootval=postorder[postRight];//从后序遍历获得根元素
TreeNode root=new TreeNode(rootval);
int rootIndex=0;
//找到根元素在中序遍历的位置
for(int i=inLeft;i<=inRight;i++){
if(inorder[i]==rootval){
rootIndex=i;
break;
}
}
// 根据rootIndex划分左右子树
root.left=build(inorder,inLeft,rootIndex-1,postorder,postLeft,postLeft+(rootIndex-1-inLeft));
root.right=build(inorder,rootIndex+1,inRight,postorder,postRight-1-(inRight-rootIndex-1),postRight-1);
return root;
}
Leetcode105-从前序遍历与中序遍历序列构造二叉树
- 给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
- 输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
- 输出: [3,9,20,null,null,15,7]
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public static TreeNode build(int[] preorder,int preleft,int preright,int[] inorder,int inleft,int inright){
if(inright-inleft<0){
return null;
}
if(inright-inleft==0){
return new TreeNode(inorder[inright]);
}
int rootval=preorder[preleft];
TreeNode root=new TreeNode(rootval);
int rootIndex=0;
for(int i=inleft;i<=inright;i++){
if(inorder[i]==rootval){
rootIndex=i;
break;
}
}
root.left=build(preorder,preleft+1,preleft+1+(rootIndex-1-inleft),inorder,inleft,rootIndex-1);
root.right=build(preorder,preright-(inright-rootIndex-1),preright,inorder,rootIndex+1,inright);
return root;
}
Leetcode654-最大二叉树
- 给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
- 创建一个根节点,其值为
nums
中的最大值。 - 递归地在最大值 左边 的 子数组前缀上 构建左子树。
- 递归地在最大值 右边 的 子数组后缀上 构建右子树。
- 输入:nums = [3,2,1,6,0,5]
- 输出:[6,3,5,null,2,0,null,null,1]
public TreeNode constructMaximumBinaryTree(int[] nums) {
return construct(nums,0,nums.length-1);
}
public static TreeNode construct(int[] nums,int leftIndex,int rightIndex){
if(rightIndex-leftIndex<0){
return null;
}
if(rightIndex-leftIndex==0){
return new TreeNode(nums[leftIndex]);
}
int max=nums[leftIndex];
int maxIndex=leftIndex;
for(int i=leftIndex;i<=rightIndex;i++){
if(nums[i]>max){
max=nums[i];
maxIndex=i;
}
}
TreeNode root=new TreeNode(max);
root.left=construct(nums,leftIndex,maxIndex-1);
root.right=construct(nums,maxIndex+1,rightIndex);
return root;
}