• LeetCode 107. Binary Tree Level Order Traversal II


    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,null,null,15,7],

    
    
    

    return its bottom-up level order traversal as:

    
    
    

    c++:

    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            
           queue<TreeNode*> q;
           queue<int> q2;
           vector<vector<int> > ans;
           if(root==NULL)
               return ans;
           q.push(root);q2.push(0);
           vector<int> res;
           int j=-1;
           while(!q.empty())
           {
               TreeNode* term = q.front();
               int i = q2.front();
               if(i==j+2)
               {
                   ans.push_back(res);
                   res.clear();
                   j++;
               }
               res.push_back(term->val);     
               q.pop();q2.pop();
               if(term->left!=NULL)
               { q.push(term->left);q2.push(i+1);}
               if(term->right!=NULL)
               { q.push(term->right);q2.push(i+1);}
           }
           if(!res.empty())
               ans.push_back(res);
            
            vector<vector<int> > result;
            int n = ans.size()-1;
            for(int i=ans.size()-1;i>=0;i--)
            {
                result.push_back(ans[i]);
            }
            
           return result;
            
        }
  • 相关阅读:
    032 代码复用与函数递归
    031 实例7-七段数码管绘制
    030 函数的定义与使用
    029 函数和代码复用
    2.4 Buffer
    2.3 字符串链接
    2.2 去除字符串特别字符
    2.1 字符串查询
    存储数据_文件读写
    template模板
  • 原文地址:https://www.cnblogs.com/dacc123/p/9226495.html
Copyright © 2020-2023  润新知