【LeetCode】129. Sum Root to Leaf Numbers

时间:2022-09-05 21:20:18

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
/ \
2 3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

题解:

  类似于 Path Sum 和  Path Sum II,迭代方法依然是后序遍历的思路,先遍历左右孩子。

Solution 1

 class Solution {
public:
int sumNumbers(TreeNode* root) {
if (!root)
return ;
return dfs(root, );
}
int dfs(TreeNode* root, int sum) {
if (!root)
return ;
sum = sum * + root->val;
if (!root->left && !root->right)
return sum;
return dfs(root->left, sum) + dfs(root->right, sum);
}
};

Solution 2

 class Solution {
public:
int sumNumbers(TreeNode* root) {
if (!root)
return ;
queue<TreeNode*> q1;
queue<int> q2;
q1.push(root);
q2.push(root->val); int sum = , cursum = ;
TreeNode* cur = root; while (!q1.empty()) {
cur = q1.front();
cursum = q2.front();
q1.pop();
q2.pop(); if (!cur->left && !cur->right) {
sum += cursum;
}
if (cur->left) {
q1.push(cur->left);
q2.push(cursum * + cur->left->val);
}
if (cur->right) {
q1.push(cur->right);
q2.push(cursum * + cur->right->val);
}
}
return sum;
}
};

Solution 3

 class Solution {
public:
int sumNumbers(TreeNode* root) {
if (!root)
return ;
stack<TreeNode*> s1;
stack<int> s2;
int sum = , cursum = ;
TreeNode* cur = root, *pre = nullptr;
while (cur || !s1.empty()) {
while (cur) {
s1.push(cur);
cursum = cursum * + cur->val;
s2.push(cursum);
cur = cur->left;
}
cur = s1.top();
if (!cur->left && !cur->right) {
sum += cursum;
}
if (cur->right && cur->right != pre) {
cur = cur->right;
} else {
pre = cur;
s1.pop();
cursum = s2.top();
s2.pop();
cursum -= cur->val;
cursum /= ;
cur = nullptr;
}
}
return sum;
}
};