C++ 中包含所有最深節點的最小子樹
假設我們有一棵根節點為 root 的二叉樹,每個節點的深度是到根節點的最短距離。如果一個節點擁有在整棵樹中所有節點中最大的深度,則稱該節點是最深的節點。一個節點的子樹包含該節點及其所有後代節點。我們需要找到深度最大的節點,並且該節點的子樹包含所有最深的節點。

那麼最深的子樹將是:

為了解決這個問題,我們將遵循以下步驟:
定義一個名為 solve() 的方法,該方法將 root 作為輸入。
如果 root 為空,則返回 (null, 0)。
l := solve(root 的左子樹),r := solve(root 的右子樹)。
如果左子樹的第二個值 > 右子樹的第二個值,則返回一個對 (l 的第一個值, 1 + l 的第二個值)。
否則,如果左子樹的第二個值 < 右子樹的第二個值,則返回一個對 (r 的第一個值, 1 + r 的第二個值)。
返回一個對 (root, 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]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP