N-ary Tree
unknown
c_cpp
3 years ago
1.3 kB
12
Indexable
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
vector<Node *> child;
};
Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
return temp;
}
int findDepthOfTree(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 countX(Node * root,int x)
{
int count = 0;
if(root == nullptr){
return 0;
}
if(root->data==x){
count++;
}
for(auto child : root->child){
count+=countX(child,x);
}
return count;
}
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(3));
root->child[2]->child.push_back(newNode(3));
root->child[2]->child.push_back(newNode(4));
cout << findDepthOfTree(root) << endl;
cout<<"so lan xuat hien cua x la "<<countX(root,3)<<endl;
return 0;
}
Editor is loading...