ETH官方钱包

前往
大廳
主題

C/C++紀錄三十二<#589 N-ary Tree Preorder Traversal> 2018/12/27

艾倫D索妮雅 | 2021-06-09 19:50:37 | 巴幣 0 | 人氣 135

#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;
class Node
{
public:
   int val;
   vector<Node*> children;
     Node()
{
//建構式為空
}
     Node(int _val, vector<Node*> _children)
{
         val = _val;
         children = _children;
     }
};
class Solution
{
public:
vector<int> v;
        vector<int> preorder(Node* root)
        {
            if(root == NULL ) return {};
            v.push_back(root->val) ;
            for(int i=0; i < root->children.size(); i++)
            {
                preorder(root->children[i]);
            }
            return v;    
        }
        Node *insert_node(Node *root,int data)
        {
         Node *current;
         Node *newnode;
         newnode=new (Node);
         newnode->val=data;
         if(root==NULL)
         {
         root=newnode;
         return root;
}
else
{
if(root->children.size()<3)
root->children.push_back(newnode);
else
{
current=root->children[0];
current->children.push_back(newnode);
}
return root;
}
}
Node *create_tree(int *data,int len)
{
Node *root=NULL;
int i;
for(i=0;i<len;i++)
{
root=insert_node(root,data[i]);
}
return root;
}
};
int main()
{
int i;
int data[6]={1,3,2,4,5,6};
Node *Ntree;
Solution operate;
vector<int> arr;
Ntree=operate.create_tree(data,6);
arr=operate.preorder(Ntree);
for(i=0;i<arr.size();i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
system("PAUSE");
return 0;
}

創(chuàng)作回應

相關創(chuàng)作

更多創(chuàng)作