欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode【112】Path Sum

程序员文章站 2024-01-05 11:23:40
...

问题描述:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

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.

源码:

还是递归大法,时间69%,空间100%。

/**
 * 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)   return false;
        if(!root->left && !root->right && root->val == sum)     return true;
        bool res = false;
        if(root->left)   res |= hasPathSum(root->left, sum - root->val);
        if(root->right)   res |= hasPathSum(root->right, sum - root->val);
        return res;
    }
};

再来看看非递归的。

/**
 * 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)   return false;
        queue<pair<TreeNode*, int>> st;
        st.push(make_pair(root, sum - root->val));
        while(!st.empty()){
            auto tmp = st.front();
            // cout<<tmp.second<<endl;
            st.pop();
            if(tmp.second==0 && !tmp.first->left && !tmp.first->right)   return true;
            // if(tmp.second<=0)   continue;
            if(tmp.first->left)  st.push(make_pair(tmp.first->left, tmp.second - tmp.first->left->val));
            if(tmp.first->right)  st.push(make_pair(tmp.first->right, tmp.second - tmp.first->right->val));
        }
        return false;
    }
};

 

上一篇:

下一篇: