LeetCode 589,590:N叉树的前序遍历和后序遍历

女票在阿里视频面的时候被问到了这个题,值得注意下。

题目

这里写图片描述
这里写图片描述

思路

N叉树的结构如下:

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

    Node() {}

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

比二叉树麻烦些,子节点被存储在vector容器中,在判断是否有子节点时只需要判断子节点容器的长度即可;而对子节点的操作就直接对容器中的元素进行遍历。整体操作还是很容易的。

和二叉树一样,遍历问题通过递归法操作很容易,不多讲,直接看代码吧。至于先序遍历和后序遍历只是父节点返回位置的问题。

代码

前序遍历

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> preorder(Node* root) {
        vector<int> t;
        if(!root)
            return t;
        t.push_back(root->val);

        if(root->children.size())
        {
            for(int i=0;i<root->children.size();i++)
            {
                vector<int> temp=preorder(root->children[i]);
                t.insert(t.end(),temp.begin(),temp.end());
            }
        }
        return t;
    }
};

后序遍历

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> t;
        if(!root)
            return t;

        if(root->children.size())
        {
            for(int i=0;i<root->children.size();i++)
            {
                vector<int> temp=postorder(root->children[i]);
                t.insert(t.end(),temp.begin(),temp.end());
            }
        }
        t.push_back(root->val);
        return t;
    }
};

这里有个小插曲,一开始我在把递归返回的数组插入到t中时,写成了:
t.insert(t.end()-1,temp.begin(),temp.end());
这样就等于把子节点数组始终放在父节点的前面,这样不需要改动父节点的返回位置,就可以实现后序遍历。

猜你喜欢

转载自blog.csdn.net/lin453701006/article/details/81699476