构造二叉树

 

class Solution {
public:
    //--入口函数
    TreeNode* constructMaximumBinaryTree(vector<int>& nums){
        return buildEachNode(nums,0,nums.size()-1);
    }

    //--主功能函数
    /*
    思路:
    对于【构造二叉树】的问题,【根节点】要做的就是想办法【把自己构造出来】。
    之后,对左右子节点,递归调用构造根节点的函数,实现递归遍历数,创建子节点的效果。
    本题中,对于每个根节点,只需要找到当前 nums 中的最大值和对应的索引,然后递归调用左右数组构造左右子树即可。
    */
    TreeNode* buildEachNode(vector<int>& nums, int sta, int end){
        if(nums.empty()){//特殊情况返回NULL
            return nullptr;
        }

        //--分割数组的左边界大于右边界,即数组不能再分割,返回空
        if(sta > end){
            return nullptr;
        }

        int maxV = INT_MIN;//存储最大值
        int maxI = -1;//存储最大值的索引

        //--找到分割数组的最大值
        for(int i = sta; i <= end;i++){
            if(nums[i] > maxV){
                maxV = nums[i];
                maxI = i;
            }
        }

        //--创建当前的分割数组的最大值的节点
        TreeNode *root = new TreeNode(maxV);

        //--递归调用主功能函数,递归创建当前节点的左右子节点
        root->left = buildEachNode(nums,sta,maxI - 1);
        root->right = buildEachNode(nums,maxI + 1, end);
        
        return root;
    }
};

参考:https://labuladong.gitee.io/algo/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E7%B3%BB%E5%88%97/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%B3%BB%E5%88%972.html

posted on 2021-03-17 14:12  平ping  阅读(69)  评论(0)    收藏  举报