Leetcode 112, Path Sum

来源:互联网 发布:linux zip命令 密码 编辑:程序博客网 时间:2024/06/05 11:53

Leetcode 112, Path Sum, 难度easy

这周上的是DFS,所以就先做了这道DFS的题,解题思路就是深搜一遍,到达一个结点时先判断左右子节点是否为空,都为空说明是叶子节点,然后判断当前的和是否等于sum返回true or false,非叶子节点则进行下一步的深搜。
以下是代码:

class Solution {public:    bool hasPathSum(TreeNode* root, int sum) {        int res = 0;        if(root == NULL) return false;        else return binaryTree(root, sum, res);    }    bool binaryTree(TreeNode* root, int sum, int res) {        res += root -> val;        bool left = root -> left == NULL?  (root -> right == NULL? sum == res: false) : binaryTree(root -> left, sum, res);        bool right = root -> right == NULL? (root -> left == NULL? sum == res: false) : binaryTree(root -> right, sum, res);        if(left || right) return true;        return false;    }};
原创粉丝点击