Example #1
0
 bool hasPathSum1(TreeNode* root, int sum) {
     if (!root) {
         return false;
     }
     sum -= root->val;
     // when the left child and right child are both nullptr can root be the leaf
     // node
     if (!root->left && !root->right) {
         return sum == 0;
     }
     return hasPathSum1(root->left, sum) || hasPathSum1(root->right, sum);
 }
Example #2
0
bool hasPathSum1(struct TreeNode* root,int sum,int result){
	if(result==sum){
		if(root->left==NULL&&root->right==NULL){
			return true ;
		}
	}
	if(root->left!=NULL){
		if(hasPathSum1(root->left,sum,result+root->left->val)){
			return true ;
		}
	}
	if(root->right!=NULL){
		if(hasPathSum1(root->right,sum,result+root->right->val)){
			return true ;
		}
	}
	return false ;
	
}
Example #3
0
bool hasPathSum(struct TreeNode* root, int sum) {
	if(root==NULL){
		return false ;
	}
	int result = root->val ;
	if(hasPathSum1(root,sum,result)){
		return true ;
	}else{
		return false ;
	}
}
Example #4
0
 bool hasPathSum(TreeNode *root, int sum) {
     // dfs version
     return hasPathSum1(root, sum);
     // bfs version
     return hasPathSum2(root, sum);
 }
 bool hasPathSum(TreeNode *root, int sum) {
     if (random()%2){
         return hasPathSum1(root, sum);    
     }
     return hasPathSum2(root, sum);
 }