zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    tomcat-1
    oscache-2
    oscache-3
    oscache-1
    oscache-4
    缓存概要
    Criterion & DetachedCriteria
    Hibernate <查询缓存>
    Hibernate <二级缓存>
    Hibernate <一级缓存>
  • 原文地址:https://www.cnblogs.com/immjc/p/7225544.html
Copyright © 2011-2022 走看看