算法系列——二叉树5

404. 左叶子之和

class Solution {

public:

    //求以root为根的树的左叶子节点和

    int sumOfLeftLeaves(TreeNode* root) {

        if(!root) return 0;

        int sumLeft=sumOfLeftLeaves(root->left);

        int sumRight=sumOfLeftLeaves(root->right);

        //以上已经计算出分别求出左子树和右子树的左叶子之和,只需要求根节点的左叶子即可,只有当左孩子存在并且左孩子为叶子节点才有左叶子

        int sumroot=0;

        if(root->left&&!root->left->left&&!root->left->right){

            sumroot=root->left->val;

        }

        return sumroot+sumLeft+sumRight;

    }

};

109. 有序链表转换二叉搜索树

class Solution {

public:

    //递归先序,快排思想,与654最大二叉树类似

    TreeNode* help(vector<int>&vec,int L,int R){

        if(L>R) return nullptr;

        int mid=L+(R-L)/2;

        TreeNode* root=new TreeNode(vec[mid]);

        root->left=help(vec,L,mid-1);

        root->right=help(vec,mid+1,R);

        return root;

    }

    TreeNode* sortedListToBST(ListNode* head) {

        vector<int>vec;

        while(head){

            vec.push_back(head->val);

            head=head->next;

        }

        return help(vec,0,vec.size()-1);

    }

};

1038. 把二叉搜索树转换为累加树

class Solution {

public:/*

    从右往左累加所以遍历的顺序是右左中,并且也不需要返回值,

    只需改变一下节点的值即可

*/

    int sum=0;

    void help(TreeNode* root){

        if(!root) return;

        help(root->right);

        sum+=root->val;

        root->val=sum;

        help(root->left);

    } 

    TreeNode* bstToGst(TreeNode* root) {

        help(root);

        return root;        

    }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值