• [LeetCode] Binary Tree Level Order Traversal II


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

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7

    return its bottom-up level order traversal as:

    [
      [15,7],
      [9,20],
      [3]
    ]
    使用queue层次遍历二叉树,将每一层的元素放入一个数组中,然后将每一层的数组放入结果二维数组中,最后将结果二维数组反转即可。
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> res;
            if (root == nullptr)
                return res;
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty()) {
                int n = q.size();
                vector<int> cur;
                for (int i = 0; i != n; i++) {
                    TreeNode* node = q.front();
                    q.pop();
                    cur.push_back(node->val);
                    if (node->left != nullptr)
                        q.push(node->left);
                    if (node->right != nullptr)
                        q.push(node->right);
                }
                res.push_back(cur);
            }
            reverse(res.begin(), res.end());
            return res;
        }
    };
    // 3 ms
  • 相关阅读:
    5、垂直拆分---分库--mycat
    4、读写分离---双主双从(mycat)
    3、读写分离---一主一从(mycat)
    2、安装启动(Mycat)
    1、入门(Mycat)
    Nginx 相关参数记录(2)
    Nginx 相关参数记录(1)
    Linux
    一大波学习内容!
    开源镜像站
  • 原文地址:https://www.cnblogs.com/immjc/p/7225544.html
Copyright © 2020-2023  润新知