C++程式中N叉樹的深度
在本教程中,我們將學習如何查詢N叉樹的深度。
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
結論
如果您在本教程中有任何疑問,請在評論部分中提出。
廣告