Giả sử chúng ta có một cây nhị phân, chúng ta phải tìm tổng các giá trị của các lá sâu nhất của nó. Vì vậy, nếu cây như -
Khi đó đầu ra sẽ là 15.
Để giải quyết vấn đề này, chúng tôi sẽ làm theo các bước sau -
- Xác định bản đồ m và maxDepth
- Xác định một phương thức đệ quy giải quyết (), phương thức này sẽ lấy nút và cấp, cấp ban đầu là 0
- nếu nút không xuất hiện, thì trả về
- maxDepth:=tối đa của cấp và maxDepth
- tăng m [cấp] theo giá trị của nút
- giải quyết (bên trái của nút, mức + 1)
- giải quyết (bên phải của nút, mức + 1)
- Trong phương thức chính, hãy thiết lập maxDepth:=0, sau đó giải quyết (root, 0)
- trả lại m [maxDepth]
Ví dụ (C ++)
Hãy cùng chúng tôi xem cách triển khai sau để hiểu rõ hơn -
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
void insert(TreeNode **root, int val){
queue<TreeNode*> q;
q.push(*root);
while(q.size()){
TreeNode *temp = q.front();
q.pop();
if(!temp->left){
if(val != NULL)
temp->left = new TreeNode(val);
else
temp->left = new TreeNode(0);
return;
}
else{
q.push(temp->left);
}
if(!temp->right){
if(val != NULL)
temp->right = new TreeNode(val);
else
temp->right = new TreeNode(0);
return;
}
else{
q.push(temp->right);
}
}
}
TreeNode *make_tree(vector<int> v){
TreeNode *root = new TreeNode(v[0]);
for(int i = 1; i<v.size(); i++){
insert(&root, v[i]);
}
return root;
}
class Solution {
public:
int maxDepth;
map <int, int> m;
void solve(TreeNode* node, int level = 0){
if(!node)return;
maxDepth = max(level, maxDepth);
m[level] += node->val;
solve(node->left, level + 1);
solve(node->right, level + 1);
}
int deepestLeavesSum(TreeNode* root) {
maxDepth = 0;
m.clear();
solve(root);
//cout << maxDepth << endl;
return m[maxDepth];
}
};
main(){
vector<int> v = {1,2,3,4,5,NULL,6,7,NULL,NULL,NULL,NULL,8};
TreeNode *root = make_tree(v);
Solution ob;
cout << (ob.deepestLeavesSum(root));
} Đầu vào
[1,2,3,4,5,null,6,7,null,null,null,null,8]
Đầu ra
15