C++實現LeetCode(107.二叉樹層序遍歷之二)

[LeetCode] 107. Binary Tree Level Order Traversal II 二叉樹層序遍歷之二

Given the root of a binary tree, return the bottom-up level order traversal of its nodes’ values. (i.e., from left to right, level by level from leaf to root).

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

從底部層序遍歷其實還是從頂部開始遍歷,隻不過最後存儲的方式有所改變,可以參見博主之前的博文 Binary Tree Level Order Traversal, 參見代碼如下:

解法一:

class Solution {
public:
    vector<vector<int> > levelOrderBottom(TreeNode* root) {
        if (!root) return {};
        vector<vector<int>> res;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            vector<int> oneLevel;
            for (int i = q.size(); i > 0; --i) {
                TreeNode *t = q.front(); q.pop();
                oneLevel.push_back(t->val);
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            res.insert(res.begin(), oneLevel);
        }
        return res;
    }
};

下面來看遞歸的解法,由於遞歸的特性,我們會一直深度優先去處理左子結點,那麼勢必會穿越不同的層,所以當要加入某個結點的時候,必須要知道當前的深度,所以使用一個變量 level 來標記當前的深度,初始化帶入0,表示根結點所在的深度。由於需要返回的是一個二維數組 res,開始時由於不知道二叉樹的深度,不知道有多少層,所以無法實現申請好二維數組的大小,隻有在遍歷的過程中不斷的增加。那麼什麼時候該申請新的一層瞭呢,當 level 等於二維數組的大小的時候,為啥是等於呢,不是說要超過當前的深度麼,這是因為 level 是從0開始的,就好比一個長度為n的數組A,你訪問 A[n] 是會出錯的,當 level 等於數組的長度時,就已經需要新申請一層瞭,新建一個空層,繼續往裡面加數字,參見代碼如下:

解法二:

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> res;
        levelorder(root, 0, res);
        return vector<vector<int>> (res.rbegin(), res.rend());
    }
    void levelorder(TreeNode* node, int level, vector<vector<int>>& res) {
        if (!node) return;
        if (res.size() == level) res.push_back({});
        res[level].push_back(node->val);
        if (node->left) levelorder(node->left, level + 1, res);
        if (node->right) levelorder(node->right, level + 1, res);
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/107

類似題目:

Average of Levels in Binary Tree

Binary Tree Zigzag Level Order Traversal

Binary Tree Level Order Traversal

類似題目:

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/35089/Java-Solution.-Using-Queue

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/34981/My-DFS-and-BFS-java-solution

到此這篇關於C++實現LeetCode(107.二叉樹層序遍歷之二)的文章就介紹到這瞭,更多相關C++實現二叉樹層序遍歷之二內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: