方法一,递归。时间复杂度O(n),空间O(logN)。代码如下:
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(!root) return false;
if(root->left == NULL && root->right == NULL)
return sum == root->val;
return hasPathSum(root->left, sum-(root->val))
|| hasPathSum(root->right, sum-(root->val));
}
};
方法二,使用queue进行非递归广度BFS遍历。(用stack深度遍历也可以),主要思想是保存node和sum组成的序列,碰到跟节点就做判断。 代码如下。
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(root == NULL) return false;
queue<pair<TreeNode*,int> > queue;
queue.push(make_pair(root, sum));
while(!queue.empty()) {
TreeNode *cur = queue.front().first;
int val = queue.front().second;
queue.pop();
if(cur->left == NULL && cur->right == NULL && cur->val == val)
return true;
int remaining = val - (cur->val);
if(cur->left)
queue.push(make_pair(cur->left, remaining));
if(cur->right)
queue.push(make_pair(cur->right, remaining));
}
return false;
}
};
Method 3: search using DFS with stack
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(root == NULL) return false;
stack<pair<TreeNode*,int> > stack;
stack.push(make_pair(root, sum));
while(!stack.empty()) {
TreeNode *cur = stack.top().first;
int val = stack.top().second;
stack.pop();
if(cur->left == NULL && cur->right == NULL && cur->val == val)
return true;
int remaining = val - (cur->val);
if(cur->left)
stack.push(make_pair(cur->left, remaining));
if(cur->right)
stack.push(make_pair(cur->right, remaining));
}
return false;
}
};