129. Sum Root to Leaf Numbers
# Medium
BFS, two ways: sum = sum*10 + root.val
Queue + while loop
Recursive
x = queue.front(), 队结构先进先出,queue.pop() 弹出第一个元素,这两是一对。
Solution 1: update evey node's value with path sum from root to this node
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
queue<TreeNode*> q;
// edge case
if(root == NULL) return 0;
if(root->left == NULL and root->right == NULL) return root->val;
// regular case, BFS
q.push(root);
int sum = 0;
while(!q.empty()) {
int l = q.size();
for(int i = 0; i < l; i ++) {
root = q.front();
q.pop();
if(root->left != NULL) {
root->left->val = root->val*10 + root->left->val;
q.push(root->left);
}
if(root->right != NULL) {
root->right->val = root->val*10 + root->right->val;
q.push(root->right);
}
if(root->right == NULL and root->left == NULL) {
sum = sum + root->val;
}
}
}
return sum;
}
};
Solution 2: subTree(root, sum)
means sum path from root to all leaves, including root.
subTree(root, sum)
means sum path from root to all leaves, including root./**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode* root) {
return subTree(root, 0);
}
int subTree(TreeNode* root, int sum) {
// edge case
if(root == NULL) return 0;
// regular case, BFS, recursive
sum = sum*10 + root->val;
if(root->left == NULL and root->right == NULL) {
return sum;
}
return subTree(root->left, sum)+subTree(root->right, sum);
}
};
Last updated
Was this helpful?