#include <memory>
#include <stack>
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
//前序遍历,并且记录每个结点的路径sum
TreeNode* bt=root;
stack<TreeNode*> s;
int temp=0;//用来记录当前结点路径总和
stack<int> curSum;//用另一个栈记录s栈中每个元素的路径长度,这样即使在回溯时也能更新长度
//前序遍历
while(!s.empty()||bt!=nullptr)
{
while(bt!=nullptr)
{
s.push(bt);
//纪录遍历到的结点的路径长度
temp+=bt->val;
curSum.push(temp);
//检查当前遍历到的结点是否满足条件
if(bt->left==nullptr&&bt->right==nullptr)
{
if(temp==sum)
return true;
}
bt=bt->left;
}
if(!s.empty())
{
bt=s.top();
s.pop();
temp=curSum.top();//如果回溯了,应当使用curSum中的元素更新temp
curSum.pop();
bt=bt->right;
}
}
return false;
}
};
前序遍历二叉树,并在遍历时记录和判断每个结点的路径总和



京公网安备 11010502036488号