★【递归前序】【构造二叉树】LeetCode 654 最大二叉树
凡是构造二叉树>>>>>>>>>>前序遍历(中左右)
---------------🎈🎈题目链接🎈🎈-------------------
方法一:递归前序 类似由 前序中序 / 后序中序 构造二叉树
1、找到最大值max以及其所在的maxindex
2、切割左右数组
3、递归left right子树
/**
* 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 constructMaximumBinaryTree(int[] nums) {
return helper(nums,0,nums.length-1);
}
public TreeNode helper(int[] nums,int begin, int end){
if(begin>end)return null;
if(nums.length ==0) return null;
int max = -1;
int maxindex = 0;
for(int i = begin; i<=end; i++){ // 找到最大值max以及其所在的maxindex
if(nums[i] > max){
max = nums[i];
maxindex = i;
}
}
TreeNode root= new TreeNode(max);
// 切割左右数组
int leftbegin = begin;
int leftend = maxindex-1;
int rightbegin = maxindex+1;
int rightend = end;
// 递归left right子树
root.left = helper(nums,leftbegin,leftend);
root.right = helper(nums,rightbegin,rightend);
return root;
}
}
方法二:自己写的比方法一差 随便看看
拿到最大值
拿到最大值对应的index
切割左右数组
之后递归root.left, root.right左右子树
Arrays.copyOfRange(nums,begin,end+1)
切割数组
/**
* 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 constructMaximumBinaryTree(int[] nums) {
return helper(nums,0,nums.length-1);
}
public TreeNode helper(int[] nums,int begin, int end){
if(begin>end)return null;
if(nums.length ==0) return null;
int max;
if(begin==end){
max = nums[begin];
}else{
int[] numssort =Arrays.copyOfRange(nums,begin,end+1);
Arrays.sort(numssort);
max = numssort[numssort.length-1]; // 拿到最大值
}
TreeNode root= new TreeNode(max);
int maxindex;
for(maxindex = begin; maxindex<nums.length; maxindex++){ // 找到最大值所在的id
if(nums[maxindex]==max){
break;
}
}
// 切割左右数组
int leftbegin = begin;
int leftend = maxindex-1;
int rightbegin = maxindex+1;
int rightend = end;
// 递归left right子树
root.left = helper(nums,leftbegin,leftend);
root.right = helper(nums,rightbegin,rightend);
return root;
}
}