zoukankan      html  css  js  c++  java
  • 【LeetCode】107

    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,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    Solution 1: 普通层次遍历,借助queue

    /**
     * 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) {      //runtime: 8ms
            vector<vector<int>> vec;
            if(!root)return vec;
            vector<int> v;
            
            queue<TreeNode*> q1,q2;
            q1.push(root);
            while(!q1.empty()){
                TreeNode* temp = q1.front();
                q1.pop();
                v.push_back(temp->val);
                if (temp->left)
                    q2.push(temp->left);
                if (temp->right)
                    q2.push(temp->right);
                
                if(q1.empty()){
                    if (!v.empty())
                        vec.push_back(v);
                    v.clear();
                    swap(q1, q2);
                }
            }
            reverse(vec.begin(),vec.end());    //or vector<vector<int>> ret(vec.rbegin(),vec.rend());return ret;
         return vec;
       }
    }

    Solution 2: 递归, 待续

  • 相关阅读:
    linux常用命令中篇
    htaccess正则规则学习笔记整理
    个性签名
    求函数的单调区间
    函数的奇偶性
    函数的对称性
    函数的周期性
    复合函数
    赋值法
    高中数学中高频变形技巧收录
  • 原文地址:https://www.cnblogs.com/irun/p/4734533.html
Copyright © 2011-2022 走看看