LeetCode112.路径总和

题目来源:https://leetcode-cn.com/problems/path-sum/description/

题目描述:

算法描述: 

1.如果根节点为NULL,直接返回false。否则调用check函数

2.当遍历完一条路径之后,如果sum==a,返回true。否则返回false

3.如果左子树为空,右子树不为空。则右子树递归。如果右子树为空,左子树不为空。则左子树递归

4如果左右子树都不为空,左右子树进行递归,只要其中一条路径返回true。那最后的结果就是true

代码如下:

bool check(struct TreeNode* t, int sum, int a) {
	//当遍历完一条路径之后,如果sum==a,返回true。否则返回false
    if(t == NULL) return (sum == a);
    //如果左子树为空,右子树不为空。则右子树递归
    if(t->left == NULL&&t->right != NULL) return check(t->right, sum+t->val, a);
    //如果右子树为空,左子树不为空。则左子树递归
    if(t->left != NULL&&t->right == NULL) return check(t->left, sum+t->val, a);
    //如果左右子树都不为空,左右子树进行递归,只要其中一条路径返回true。那最后的结果就是true
    return check(t->left, sum+t->val, a)||check(t->right, sum+t->val, a);
}
bool hasPathSum(struct TreeNode* root, int sum) {
    if(root == NULL) return false;
    return check(root, 0, sum);
}

猜你喜欢

转载自blog.csdn.net/qq_39241239/article/details/82749696