루트에 뿌리를 둔 이진 트리가 있다고 가정하면 각 노드의 깊이는 루트까지의 최단 거리입니다. 여기서 노드는 전체 트리의 노드 중에서 가능한 가장 큰 깊이를 가질 때 가장 깊습니다. 노드의 하위 트리는 해당 노드와 해당 노드의 모든 하위 항목 집합입니다. 하위 트리에서 가장 깊은 노드를 모두 포함하도록 가장 큰 깊이를 가진 노드를 찾아야 합니다. 트리가 다음과 같다면 -

그러면 가장 깊은 하위 트리는 -
가 됩니다.

이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
solve()라는 메서드를 정의하면 입력으로 루트가 됩니다.
-
루트가 null이면 (null, 0)
을 반환합니다. -
l :=해결(루트의 왼쪽), r :=해결(루트의 오른쪽)
-
왼쪽의 두 번째 값> r의 두 번째 값이면 쌍을 반환합니다(l의 첫 번째, 1 + l의 두 번째)
-
그렇지 않으면 왼쪽의 두 번째 값
-
쌍을 반환(루트, l + 1의 두 번째)
-
기본 메소드에서 solve(root)를 호출하고 두 번째 값을 반환합니다.
예(C++)
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int data){
val = data;
left = 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;
}
void tree_level_trav(TreeNode*root){
if (root == NULL) return;
cout << "[";
queue<TreeNode *> q;
TreeNode *curr;
q.push(root);
q.push(NULL);
while (q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL){
q.push(NULL);
} else {
if(curr->left)
q.push(curr->left);
if(curr->right)
q.push(curr->right);
if(curr->val == 0 || curr == NULL){
cout << "null" << ", ";
} else {
cout << curr->val << ", ";
}
}
}
cout << "]"<<endl;
}
class Solution {
public:
pair <TreeNode*, int> solve(TreeNode* root){
if(!root || root->val == 0) return {NULL, 0};
pair <TreeNode*, int> L = solve(root->left);
pair <TreeNode*, int> R = solve(root->right);
if(L.second > R.second)return {L.first, L.second + 1};
else if(L.second < R.second) return {R.first, R.second + 1};
return {root, L.second + 1};
}
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return solve(root).first;
}
};
main(){
vector<int> v = {3,5,1,6,2,0,8,NULL,NULL,7,4};
TreeNode *root = make_tree(v);
Solution ob;
tree_level_trav(ob.subtreeWithAllDeepest(root)) ;
} 입력
{3,5,1,6,2,0,8,NULL,NULL,7,4} 출력
[2,7,4]