N叉树的前序遍历 ( 使用数组实现 N叉树 )

一、N叉树的节点 Node 定义如下:

class Node
{
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};

二、根据层序遍历的结果数组,构造 N叉树:

#include <iostream>
#include<vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;

class Node
{
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};

class Solution {
public:
    vector<int> preorder(Node* root) {
        if (root == NULL) return {};
        cout << "enter:" << root->val << endl;
        childarr.push_back(root->val);
        for (Node* child : root->children)
        {
            preorder(child);
        }
        cout << "Leave:" << root->val << endl;
        return childarr;
    }

private:
    vector<int> childarr;
};
//      1
//    / | \
//   3  2  4
//  / \
// 5   6

int main()
{
    //给出N叉树的层序遍历 数组
    vector<int> root = { 1, NULL, 3, 2, 4, NULL, 5, 6 };
    //根据层序遍历的结果 ,构造出多叉树
    Node Tree[6];
    for (int i=0,j=0;i<6 && j<8 ;i++,j++)
    {
        while (root[j]==NULL)
        {
            j++;
        }
        Tree[i].val = root[j];
    }
    Tree[0].children.push_back(&Tree[1]);
    Tree[0].children.push_back(&Tree[2]);
    Tree[0].children.push_back(&Tree[3]);
    Tree[1].children.push_back(&Tree[4]);
    Tree[1].children.push_back(&Tree[5]);

    Solution todo;
    //N叉树的前序遍历
    vector<int> result = todo.preorder(Tree);

    //前序遍历的结果 打印
    for (auto it = result.begin();it!=result.end();it++)
    {
        cout<<" "<<*it;
    }
}

三、运行结果:

 结果中,打印出的enter  和 Leave 是 深度优先遍历的 进入 和 回溯 的节点。 

for 循环里面和外面 唯一的区别就 是对根节点的处理

如果更改成在for循环里面打印,结果如下:

class Solution {
public:
    vector<int> preorder(Node* root) {
        if (root == NULL) return {};
        
        childarr.push_back(root->val);
        //在 for 循环里 打印
        for (Node* child : root->children)
        {
            cout << "enter:" << child->val << endl;
            preorder(child);
            cout << "Leave:" << child->val << endl;
        }
       
        return childarr;
    }

private:
    vector<int> childarr;
};

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值