1. 程式人生 > >【LeetCode】589. N叉樹的前序遍歷、590. N叉樹的後序遍歷

【LeetCode】589. N叉樹的前序遍歷、590. N叉樹的後序遍歷

題目描述

給定一個 N 叉樹,返回其節點值的 前序遍歷 和 後續遍歷 。

例如,給定一個 3叉樹 :

返回其前序遍歷: [1,3,5,6,2,4];

返回其後序遍歷: [5,6,3,2,4,1]。

思路

遞迴法非常簡單,root 為空時直接為空,否則迴圈呼叫子節點輸出val即可;

迭代法需要利用棧,前序遍歷時,先將當前元素放入 res,然後從後往前入棧元素,棧不空時再輸出元素;

後序遍歷時,先將當前元素放入 res,然後從前往後入棧元素,棧不空時再輸出元素,最後再將 res 顛倒(可用方法 reverse(res.begin(), res.end());),返回 res 即為結果。

程式碼(前序)

/*
// 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> res;
        if(root == NULL) return res;
        stack<Node*> s;
        s.push(root);
        while(!s.empty()) {
            Node* node = s.top();
            s.pop();
            res.push_back(node->val);
            for(int i=node->children.size()-1; i>=0; i--) {
                s.push(node->children[i]);
            }
        }
        return res;
    }
};