Path sum

new 和直接定义的区别

new在堆上,需要自己释放内存空间。

直接定义的话是在栈上。

如果构造函数中没有初始化值的话,就不会分配内存。

返回值是0是false

上面是自己胡乱记录的一些东西。now use English to describe the problem.

1.we can use unordered_map<TreeNode *, bool> visited to record whether the node is visited.

2.I give the value -10000 to record whether the node is visited. However, this gives the wrong value when you pop the stack.

/**
 * Definition for binary tree
 * 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) {
    stack<TreeNode *> s;
    unordered_map<TreeNode *, bool> visited;
    int sum_stack = 0;
    if(root == NULL)
        return false;
    s.push(root);
    sum_stack = root->val;
    visited[root] = true;
    while(!s.empty())
    {
        TreeNode * temp = s.top();
        if(temp->left!=NULL && !visited[temp->left])
        {
            s.push(temp->left);
            sum_stack += temp->left->val;
            visited[temp->left] = true;
            continue;
        }
        if(temp->right!=NULL && !visited[temp->right])
        {
            s.push(temp->right);
            sum_stack += temp->right->val;
            visited[temp->right] = true;
            continue;
        }
        if(sum_stack == sum && temp->left == NULL && temp->right == NULL)
            return true;
        else{
            sum_stack -=s.top()->val;
            s.pop();
        }
        
    }
    return false;
}

};


    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值