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