Path Sum
Q:
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.
For 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.
A:
额,仍然是后序,好吧,有一点小变化,看来写一次代码能套用n多次。
/** * 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) { // Start typing your C/C++ solution below // DO NOT write int main() function if (!root) return false; stack<TreeNode*> s; stack<bool> r; int cur_sum = 0; TreeNode* cur = root; while (cur || !s.empty()) { while (cur) { s.push(cur); r.push(false); cur_sum += cur->val; cur = cur->left; } while (!r.empty() && r.top()) { TreeNode* tmp = s.top(); if (!tmp->left && !tmp->right) { if (cur_sum == sum) return true; } cur_sum -= tmp->val; s.pop(); r.pop(); } if (!s.empty()) { cur = s.top()->right; r.top() = true; } } return false; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号