[LeetCode] N-ary Tree Preorder Traversal N叉樹的前序走訪

來源:互聯網
上載者:User

標籤:child   注意   結果   參考   圖片   note   return   problem   solution   

 

 

Given an n-ary tree, return the preorder traversal of its nodes‘ values.

For example, given a 3-ary tree:

 

 

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

 

Note:

Recursive solution is trivial, could you do it iteratively?

 

這道題讓我們求N叉樹的前序走訪,有之前那道Binary Tree Preorder Traversal的基礎,知道了二叉樹的前序走訪的方法,很容易就可以寫出N叉樹的前序走訪。先來看遞迴的解法,主要實現一個遞迴函式即可,判空之後,將當前結點值加入結果res中,然後遍曆子結點數組中所有的結點,對每個結點都調用遞迴函式即可,參見代碼如下:

 

解法一:

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

 

我們也可以使用迭代的解法來做,使用棧stack來輔助,需要注意的是,如果使用棧的話,我們遍曆子結點數組的順序應該是從後往前的,因為棧是後進先出的順序,所以需要最先遍曆的子結點應該最後進棧,參見代碼如下:

 

解法二:

class Solution {public:    vector<int> preorder(Node* root) {        if (!root) return {};        vector<int> res;        stack<Node*> st{{root}};        while (!st.empty()) {            Node* t = st.top(); st.pop();            res.push_back(t->val);            for (int i = (int)t->children.size() - 1; i >= 0; --i) {                st.push(t->children[i]);            }        }        return res;    }};

 

類似題目:

Binary Tree Preorder Traversal

N-ary Tree Level Order Traversal

N-ary Tree Postorder Traversal

 

參考資料:

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

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

 

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

[LeetCode] N-ary Tree Preorder Traversal N叉樹的前序走訪

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.