Share my code backtrack and Bfs


  • 0
    Y

    backtrack:

    int sumNumbers(TreeNode* root) {
        vector<int> path;
        int res=0;
        if(!root)   return 0;
        bk(root,path,res);
        return res;
    }
    void bk(TreeNode* root,vector<int>& path,int& res){
        if(!root)   return ;
        if(!root->left&&!root->right){
            path.push_back(root->val);
            int r=0;
            for(auto i:path)
                r=r*10+i;
            res+=r;
            path.pop_back();
            return ;
        }else{
        path.push_back(root->val);
        bk(root->left,path,res);
        bk(root->right,path,res);
        path.pop_back();
        }
    }
    

    bfs:

    queue<TreeNode*> q;
        int res=0;
        if(!root)   return 0;
        q.push(root);
        while(!q.empty()){
            int len=q.size();
            while(len--){
                TreeNode* tem=q.front();
                q.pop();
                if(tem->left==NULL&&tem->right==NULL)
                    res+=tem->val;
                if(tem->left!=NULL){
                    tem->left->val=tem->val*10+tem->left->val;
                    q.push(tem->left);
                }
                if(tem->right!=NULL){
                    tem->right->val=tem->val*10+tem->right->val;
                    q.push(tem->right);
                }
            }
        }
        return res;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.