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;
}
};