多叉樹的遍歷

429. N叉樹的層序遍歷

給定一個 N 叉樹,返回其節點值的層序遍歷。 (即從左到右,逐層遍歷)。
img
返回其層序遍歷:

[
     [1],
     [3,2,4],
     [5,6]
]

說明:

  1. 樹的深度不會超過 1000
  2. 樹的節點總數不會超過 5000
class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        //特判
        if(root == nullptr) return {};
        vector<vector<int>> res;
        queue<Node*> qu;
        qu.push(root);
        while(!qu.empty()){
            vector<int> temp;
            //每一層的個數
            int size = qu.size();
            for(int i = 0; i < size; i++){
                Node* node = qu.front();
                temp.push_back(qu.front()->val);
                //遍歷隊頭的孩子節點,如果不爲空,加入隊列
                for (auto node : qu.front()->children) {
                    if (node){
                        qu.push(node);
                    }
                }
                qu.pop();
            }
            res.push_back(temp);
        }
        return res;
    }
};
/*
// Definition for a 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;
    }
};
*/

589. N叉樹的前序遍歷

難度簡單83

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

例如,給定一個 3叉樹 :

img

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

1.遞歸解法

class Solution {
    vector<int> res;
public:
    vector<int> preorder(Node* root) {
        if(!root)   return{};
        res.push_back(root->val);
        for(auto p : root->children){
            preorder(p);
        }
        return res;
    }
};

2.迭代解法

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

590. N叉樹的後序遍歷

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

例如,給定一個 3叉樹 :

img

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

分析:多叉樹的後序遍歷,仍然是左->右->根的順序,只不過這裏的左右是從左到右的順序。N叉樹的前序遍歷類似, 但子樹的入棧順序爲從左到右,最後將數組反轉一下

class Solution {
public:
    vector<int> postorder(Node* root) {
        vector<int> v;

        if(!root) return v;
       
        stack<Node*> s;
        s.push(root);

        while(!s.empty()){
            Node* node = s.top();
            v.push_back(node->val);
            s.pop();

            //從左到右入棧
            for(int i = 0 ; i < node->children.size(); ++i){
                if(node->children.at(i)) //非空結點才入棧
                    s.push(node->children.at(i));
            }
        }

        //將v反轉
        reverse(v.begin(), v.end());

        return v;       
    }
};

另外因爲多叉樹有多個分叉,因此就沒有中序遍歷的概念了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章