zoukankan      html  css  js  c++  java
  • 【Leetcode】二叉树的层次遍历

    题目:

    给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

    例如:

    思路:采用宽度优先搜索。

    时间复杂度:O(n)。n为节点的数量,遍历所有节点。

    空间复杂度:O(n)。创建一个vector容器存储所有节点值。

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector< vector<int> > result;
            if (root == NULL)
                return result;
            
            queue<TreeNode*> q;
            q.push(root);
            
            while(!q.empty()) {
                int len = q.size();
                vector<int> temp;
                
                for (int i = 0; i < len; ++i) {
                    TreeNode* node = q.front();
                    q.pop();
                    temp.push_back(node->val);
                    
                    if(node->left != NULL)
                        q.push(node->left);
                    if(node->right != NULL)
                        q.push(node->right);
                }
                result.insert(result.begin(), temp);
            }
            return result;   
        }
    };
  • 相关阅读:
    HTML笔记
    html文本格式化
    标题大小与字体大小的关系
    html学习笔记
    冒泡排序
    直接插入算法
    绘制针状图
    绘制矢量图
    饼图pie 或者pie3
    三维直方图
  • 原文地址:https://www.cnblogs.com/gdut-gordon/p/11642940.html
Copyright © 2011-2022 走看看