在本教程中,我们将学习如何找到n元树的深度。
一元树是一棵树,其中该树的每个节点不超过n个子节点。
我们必须找到n元树的深度。我们将使用向量将每个节点的子级存储在树中。
让我们看看解决问题的步骤。
用伪数据初始化树。
编写一个递归函数以查找n元树的深度。
最大深度是当前最大深度和节点子节点的深度中的最大值。
如果我们假设最大深度变量为maxDepth且maxDepth = max(maxDepth),则findDepthOfTree(* children)是查找树的深度的递归语句。
初始化变量以存储树的最大深度。
遍历每个节点的子级。
树的最终最大深度为maxDepth + 1。
打印树的最大深度。
让我们看一下代码。
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
vector<Node *> child;
};
Node *newNode(int data) {
Node *temp = new Node;
temp->data = data;
return temp;
}
int findDepthOfTree(struct Node *node) {
if (node == NULL) {
return 0;
}
int maxDepth = 0;
for (vector<Node*>::iterator it = node->child.begin(); it != node->child.end(); it++) {
maxDepth = max(maxDepth, findDepthOfTree(*it));
}
return maxDepth + 1;
}
int main() {
Node *root = newNode(1);
root->child.push_back(newNode(2));
root->child.push_back(newNode(3));
root->child.push_back(newNode(4));
root->child[2]->child.push_back(newNode(1));
root->child[2]->child.push_back(newNode(2));
root->child[2]->child.push_back(newNode(3));
root->child[2]->child.push_back(newNode(4));
cout << findDepthOfTree(root) << endl;
return 0;
}输出结果如果运行上面的代码,则将得到以下结果。
3