For example:
Given the below binary tree and
sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.解法 :
基本上就是用DFS, DFS有兩種。一種是遞迴,另外一種是用stack
遞迴法
邏輯大概是這樣,遞迴的function中先檢查傳進來的節點的三種條件
1. nullptr
這不用多說,直接回false
2. 葉子
如果是的話就在檢查傳進來的值是不是等於此節點的值,是的話就回傳true,不是就是false
3. 不是上面兩種情況
將此節點的左右子節點帶入遞迴的function然後傳入sum - 此節點的值,取兩者遞迴function的OR值
/**
* 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 == nullptr)
return false;
return hasPathSumDFS(root, sum);
}
bool hasPathSumDFS(TreeNode* node, int sum)
{
if (node == nullptr)
{
return false;
}
if (node->left == nullptr && node->right == nullptr)
{
if(node->val == sum)
{
return true;
}
else
{
return false;
}
}
return hasPathSumDFS(node->left, sum - node->val) || hasPathSumDFS(node->right, sum - node->val);
}
};
沒有留言 :
張貼留言