[LeetCode]Path Sum

来源:互联网 发布:数据如何做韦恩图 编辑:程序博客网 时间:2024/05/29 15:02
思路:
深度搜索(这里采用 回溯法)

1,先决条件:找到树根
2,不变式:遍历子node,传递sum和当前和 curSum
3,结束条件:node没有子节点,判断sum 是否等于curSum
4,临界条件:树为空

很简单,一遍过。 


/** * 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:    bool hasPathSum(TreeNode* root, int sum) {        if (root == NULL){            return false;        }        return bfs(root, sum, 0);    }    bool bfs(TreeNode* node, int sum, int curSum){        if(node->left == NULL && node->right == NULL){            return sum == (curSum + node->val);        }else{            if (node->left != NULL){                if ( bfs(node->left, sum, curSum + node->val) ){                    return true;                }            }            if (node->right != NULL){                if ( bfs(node->right, sum, curSum + node->val) ){                    return true;                }            }        }    }};


0 0
原创粉丝点击