c_cpp 112. Path Sum - DifficultyEasy - 2018.9.11
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 112. Path Sum - DifficultyEasy - 2018.9.11相关的知识,希望对你有一定的参考价值。
/**
* 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 == NULL) {
return false;
}
stack<TreeNode *> nodeS;
nodeS.push(root);
int addUp = root->val;
TreeNode *preNode;
bool turningBack;
while(!nodeS.empty()) {
preNode = nodeS.top();
if (preNode->left != NULL) {
turningBack = false;
addUp += preNode->left->val;
nodeS.push(preNode->left);
preNode->left = NULL;
continue;
}
if (preNode->right != NULL) {
turningBack = false;
addUp += preNode->right->val;
nodeS.push(preNode->right);
preNode->right = NULL;
continue;
}
if (addUp == sum
&& !turningBack) {
return true;
}
turningBack = true;
addUp -= preNode->val;
nodeS.pop();
}
return false;
}
};
以上是关于c_cpp 112. Path Sum - DifficultyEasy - 2018.9.11的主要内容,如果未能解决你的问题,请参考以下文章
112. Path Sum
LC.112.Path Sum
112. Path Sum
112. Path Sum
112. Path Sum
112. Path Sum