把题目的要求细化,搞清楚根节点应该做什么,然后剩下的事情抛给前/中/后序的遍历框架,千万不要跳到递归的细节里,相信你的定义

构造最大二叉树

选区_165.png
对于构造二叉树的问题,根节点要做的就是想办法把自己构造出来
我们肯定要遍历数组找到最大值maxVal,把根节点root做出来,然后对maxVal左边的数组和右边的数组进行递归调用,作为root的左右子树。
伪代码

TreeNode constructMaxImumBinaryTree(int[] nums){
if(num is empty){
return null;
}

int maxVal=Integer.MIN_VALUE;
int index=0;

for(int i=0;i<nums.length;i++){
if(nums[i]>maxVal){
maxVal=nums[i];
index=i;
     }
}

TreeNode root=new TreeNode(maxVal);
//递归调用构造左右子树
root.left=constructMaximumBinaryTree(nums[0]...index-1);
root.right=constructMaximumBinaryTree(nums[index+1...nums.length-1]);

return root;
}

对于每个根节点来说,最重要的是找到当前数组中的最大值以及它的索引,然后前序递归调用构造子树

//主函数
TreeNode constructMaximumBinaryTree(int[] nums){
return build(nums,0,nums.length-1);
}

TreeNode build(int[] nums,int lo,int hi){
//base case
if(lo>hi){
return null;
}

//找到数组中最大值和对应的索引
int index=-1,maxVal=Integer.MIN_VALUE;
for(int i=lo;i<=hi;i++){
if(maxVal<nums[i]){
maxVal=nums[i];
index=i;
}
}

TreeNode root=new TreeNode(maxVal);
//递归调用构造左右子树
root.left=build(nums,lo,index-1);
root.right=build(nums,index+1,hi);

return root;
}

根据二叉树的前序遍历结果和中序遍历结果来构造二叉树

这个框架用起来简直太爽了,我们需要考虑的是每个节点需要干什么
1.需要创建新节点,根据前序遍历的结果来找到根节点的值 root.val=preorder[start];
2.我们还需要确定左右子树在数组中的区间,这里需要添加一个新的变量值,leftNum代表的含义是
子树在数组中的长度
leftNum=index-start;
然后进行递归调用构造左右子树

 public TreeNode buildTree(int[] preorder, int[] inorder) {
            return buildTree(preorder,0,preorder.length,inorder,0,inorder.length);
    }
    
    public TreeNode buildTree(int[] preorder,int pre_start,int pre_end,int[] inorder,int in_start,int in_end){
        if(pre_start==pre_end){
            return null;
        }
        
        //前序遍历
        //构造节点
        int val =preorder[pre_start];
        TreeNode root=new TreeNode(val);
        
        int index=-1;
        for(int i=in_start;i<in_end;i++){
            if(root.val==inorder[i]){
                index=i;
                break;
            }
        }
        
        int leftNum=index-in_start;
        root.left=buildTree(preorder,pre_start+1,pre_start+leftNum+1,inorder,in_start,index);
        root.right=buildTree(preorder,pre_start+leftNum+1,pre_end,inorder,index+1,in_end);
        return root;
    }

ChangZhu
8 声望1 粉丝

但将行好事,莫要问前程