Tress,Recursion


  • 0
    B
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int f(TreeNode *root,int x){
            if(root!=NULL)
            if(root->left==NULL&&root->right==NULL)
                    if(x-root->val==0)
                       return 1;
            
             int ans=0;
            
              if(root!=NULL){
                  
                        ans|=f(root->left,x-root->val)|f(root->right,x-root->val);
                }
            return ans;
        }
        bool hasPathSum(TreeNode* root, int sum) {
            if(root!=NULL)
            return f(root,sum);
            else
                return 0;
        }
    };
    

Log in to reply
 

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