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

    Description:

    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]
    ]

    Code:

     1  vector<vector<int>> levelOrderBottom(TreeNode* root) {
     2            deque<TreeNode*>a;
     3        deque<TreeNode*>b;
     4        if (root)
     5             a.push_back(root);
     6         
     7        TreeNode*p = NULL;
     8        vector<vector<int>> result;
     9        
    10        while (!a.empty() || !b.empty())
    11        {
    12            vector<int>temp;
    13            if (!a.empty() )
    14            {
    15                 while (!a.empty() )
    16                 {
    17                p = a.front();
    18                a.pop_front();
    19                temp.push_back(p->val);
    20                if (p->left)
    21                     b.push_back(p->left);
    22                 if (p->right)
    23                     b.push_back(p->right);
    24                 }
    25                 result.push_back(temp);
    26            }
    27            else
    28            {
    29             while (!b.empty())
    30            {
    31                p = b.front();
    32                b.pop_front();
    33                temp.push_back(p->val);
    34                if (p->left)
    35                     a.push_back(p->left);
    36                if (p->right)
    37                     a.push_back(p->right);
    38            }
    39            result.push_back(temp);
    40            }
    41        }
    42        reverse(result.begin(),result.end());
    43        return result;  
    44     }
  • 相关阅读:
    Thymeleaf模板引擎语法
    kali更新软件源
    解决kali安装成功后没有声音的问题
    SSO的误区及建议
    关于 target="_blank"漏洞的分析
    好久没来了,平时一些笔记都记在印象笔记,长传一波
    BIOS基础
    CSRF的本质及防御
    linux下stricky
    CSRF与xss的区别
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4590606.html
Copyright © 2011-2022 走看看