-
Notifications
You must be signed in to change notification settings - Fork 2
/
q1022.hpp
57 lines (52 loc) · 1.34 KB
/
q1022.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//
// q1022.hpp
// LeetCode
//
// Created by NowOrNever on 09/09/2020.
// Copyright © 2020 DoubleL. All rights reserved.
//
#ifndef q1022_hpp
#define q1022_hpp
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
void question1022(){
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 {
private:
int sum = 0;
void sumRootToLeaf(TreeNode* root, int lastNumber) {
if (root) {
lastNumber = (lastNumber << 1) + root->val;
if (root->left || root->right) {
sumRootToLeaf(root->left, lastNumber);
sumRootToLeaf(root->right, lastNumber);
}else{
sum += lastNumber;
}
}
}
public:
int sumRootToLeaf(TreeNode* root) {
sum = 0;
sumRootToLeaf(root, 0);
return sum;
}
};
}
#endif /* q1022_hpp */