zoukankan      html  css  js  c++  java
  • LintCode-70.二叉树的层次遍历 II

    二叉树的层次遍历 II

    给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

    样例

    给出一棵二叉树 {3,9,20,#,#,15,7},

    按照从下往上的层次遍历为:
    [
        [15,7],
        [9,20],
        [3]
    ]

    标签

    二叉树 队列 二叉树遍历 宽度优先搜索

    code

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
        /**
         * @param root : The root of binary tree.
         * @return : buttom-up level order a list of lists of integer
         */
    public:
        vector<vector<int>> levelOrderBottom(TreeNode *root) {
            // write your code here
            
            vector<vector<int> > order;
            queue<TreeNode*> queue;
            int len;
    
            if(root == NULL) {
                return order;
            }
    
            queue.push(root);
            len = queue.size();
    
            while(!queue.empty())  {  
                vector<int> base;  
                len = queue.size();  
      
                while(len--) {
                    TreeNode *tmp=queue.front();  
                    base.push_back(tmp->val);
                    queue.pop();  
                    if(tmp->left)  
                        queue.push(tmp->left);  
                    if(tmp->right)      
                        queue.push(tmp->right);  
                }  
                order.push_back(base);  
            }  
    
            vector<vector<int> > order2;
            int i;
        
            for(i=order.size()-1; i>=0; i--) {
                order2.push_back(order[i]);
            }
    
            return order2;
        }
    };
  • 相关阅读:
    java监听者模式
    使用tc编写流量控制脚本
    Android apk集成
    就这样
    嘴不笨来试试??太好玩儿了,看看谁厉害?
    老板的三句话
    电脑设置wifi
    JDBC
    使用git的一般操作
    模板引擎Velocity学习系列
  • 原文地址:https://www.cnblogs.com/libaoquan/p/6807939.html
Copyright © 2011-2022 走看看