[LeetCode] 589. N-ary Tree Postorder Traversal N叉樹的后序遍歷


 

Given an n-ary tree, return the postorder traversal of its nodes' values.

For example, given a 3-ary tree:

 

 

Return its postorder traversal as: [5,6,3,2,4,1].

 

Note:

Recursive solution is trivial, could you do it iteratively?

 

這道題讓我們求N叉樹的后序遍歷,由於有了之前那道 Binary Tree Postorder Traversal 的基礎,了解了二叉樹的后序遍歷,則N叉樹的后序遍歷也就沒有那么難了。首先還是用遞歸來做,在遞歸函數中,判空后,遍歷子結點數組,對所有的子結點調用遞歸函數,然后在 for 循環之外在將當前結點值加入結果 res 數組,這樣才能保證是后序遍歷的順序,參見代碼如下:

 

解法一:

class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> res;
        helper(root, res);
        return res;
    }
    void helper(Node* node, vector<int>& res) {
        if (!node) return;
        for (Node* child : node->children) {
            helper(child, res);
        }
        res.push_back(node->val);
    }
};

 

我們也可以使用迭代的方法來做,這里有個小 trick,寫法跟先序遍歷十分的像,不同的就是每次把從 stack 中取的結點的值都加到結果 res 的最前面,還有就是遍歷子結點數組的順序是正常的順序,而前序遍歷是從子結點數組的后面往前面遍歷,這點區別一定要注意,參見代碼如下:

 

解法二:

class Solution {
public:
    vector<int> postorder(Node* root) {
        if (!root) return {};
        vector<int> res;
        stack<Node*> st{{root}};
        while (!st.empty()) {
            Node *t = st.top(); st.pop();
            res.insert(res.begin(), t->val);
            for (Node* child : t->children) {
                if (child) st.push(child);
            }
        }
        return res;
    }
};

 

類似題目:

Binary Tree Postorder Traversal

N-ary Tree Preorder Traversal

N-ary Tree Level Order Traversal

 

參考資料:

https://leetcode.com/problems/n-ary-tree-preorder-traversal/

https://leetcode.com/problems/n-ary-tree-postorder-traversal/discuss/147959/Java-Iterative-and-Recursive-Solutions

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM