• LintCode 二叉树的层次遍历 II


    中等 二叉树的层次遍历 II

    42%
    通过

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

    您在真实的面试中是否遇到过这个题? 
    Yes
    例子

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

        3
       / 
      9  20
        /  
       15   7

    依照从下往上的层次遍历为:

    [
      [15,7],
      [9,20],
      [3]
    

    ]

    asd
    /**
     * 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) {
             vector<vector<int>> res;
            if(root == nullptr) {
                return res;
            }
            vector<int> temp;
            queue<TreeNode*> q;
            stack<vector<int>> s;
            q.push(root);
            int i = 1;// points every level
            int j = 0;// lost point every level
            while(!q.empty()) {
                TreeNode *p = q.front();
                q.pop();
                if (p==nullptr) {
                    ++j;
                }
                else {
                   temp.push_back(p->val);
                    q.push(p->left);
                    q.push(p->right);
                }
                if (i == (temp.size() + j) && temp.size()!=0) {
                    s.push(temp);
                    temp.clear();
                    i*=2;
                    j*=2;
                }
            }
            while(!s.empty()) {
                res.push_back(s.top());
                s.pop();
            }
            return res;
        }
    };
    

  • 相关阅读:
    Django Form组件实例:登录界面[Form表单提交,Ajax提交]
    开张啦!
    CART剪枝
    TensorFlow全新的数据读取方式:Dataset API入门教程
    关于神经网络中的padding
    cs231n(一)
    协方差与pearson相关系数
    Auto Encoder
    markdown公式编辑参考
    Python使用日常
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5144676.html
Copyright © 2020-2023  润新知