zoukankan      html  css  js  c++  java
  • 107.Binary Tree Level Order Traversal II

    /**
     * Definition for binary tree
     * 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>> res;
            queue<TreeNode *> Q;
            if(root)    Q.push(root);
    
            while( !Q.empty())
            {
                int count=0;
                int levCount=Q.size();
                vector<int> levNode;
    
                while(count<levCount)
                {
                    TreeNode *curNode=Q.front();
                    Q.pop();
                    levNode.push_back(curNode->val);
                    if(curNode->left)
                        Q.push(curNode->left);
                    if(curNode->right)
                        Q.push(curNode->right);
                    count++;
                }
                res.push_back(levNode);
            }
            reverse(res.begin(),res.end());    //在上一题的基础上增加一行
            return res;
        }
    };
    
    /**
     * Definition for binary tree
     * 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>> res;
            queue<TreeNode *> Q;
            if(root)    Q.push(root);
            stack<vector<int>> stk;
            while( !Q.empty())
            {
                int count=0;
                int levCount=Q.size();
                vector<int> levNode;
    
                while(count<levCount)
                {
                    TreeNode *curNode=Q.front();
                    Q.pop();
                    levNode.push_back(curNode->val);
                    if(curNode->left)
                        Q.push(curNode->left);
                    if(curNode->right)
                        Q.push(curNode->right);
                    count++;
                }
                stk.push(levNode);   //压入栈
            }
            while(!stk.empty())       //出栈
            {
                res.push_back(stk.top());
                stk.pop();
            }
            return res;
        }
    };
    
  • 相关阅读:
    以正确的方式开源 Python 项目
    一个备胎的自我修养
    关于我们 | 读书马上
    基于libevent, libuv和android Looper不断演进socket编程
    libuv 与 libev 的对比
    OCaml Language Sucks
    Practical Common Lisp
    learning
    WebApi系列~QQ互联的引入(QConnectSDK)
    知方可补不足~用xsl来修饰xml
  • 原文地址:https://www.cnblogs.com/smallredness/p/10676787.html
Copyright © 2011-2022 走看看