Solution 1
作为后一个题的基础,应用在二叉树场景的DFS:不断向下探索,只在叶子节点判断是否链上节点的和为给定值。由于未限定树的结构,因此DFS的搜索顺序不会产生很大影响。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为树中的节点个数,搜索算法,所有的节点最多遍历一次
- 空间复杂度: O ( N ) O(N) O(N),其中 N N N为树中的节点个数,受调用函数栈深度影响,平均情况为 O ( log N ) O(\log N) O(logN),最坏情况为 O ( N ) O(N) O(N)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
return this->check(root, targetSum);
}
private:
bool check(TreeNode* node, int sumNow) {
if(node == nullptr) {
return false; // 缺省情况
}
if (node->left == nullptr && node->right == nullptr) {
return node->val == sumNow;
}
return this->check(node->left, sumNow - node->val) || this->check(node->right, sumNow - node->val);
}
};
Solution 2
Solution 1的Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def check(node: Optional[TreeNode], sumNow: int) -> bool:
if node is None:
return False
if node.left is None and node.right is None:
return sumNow == node.val
return check(node.left, sumNow - node.val) or check(node.right, sumNow - node.val)
return check(root, targetSum)