• LeetCode 103. Binary Tree Zigzag Level Order Traversal


    题目:以Z字的顺序层序输出树。

    思路:

    1. 关键在于找到规律,自己模拟一遍判断是否正确就行了。
    2. 我在这里对于偶数行(根结点为第一行),使用栈来反向存储。
    3. 另外,这LeetCode提交的效率真的是玄学,第一次提交超过40%,第二次提交超过70%,第三次提交超过100%;

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
    13         queue<TreeNode*> q;  
    14         // 出栈
    15         stack<TreeNode*> s;
    16         vector<vector<int>> v;
    17         vector<int> vv; 
    18         // 关于层
    19         int num1=1,num2=0;
    20         int level=1;   // level%1=1,顺序;=0,栈
    21         
    22         q.push(root);
    23         while(root!=NULL && !q.empty()){
    24             TreeNode* tmp=q.front();
    25             q.pop();
    26             num1--;
    27             vv.push_back(tmp->val);
    28 
    29             if(tmp->left!=NULL){
    30                 q.push(tmp->left);
    31                 num2++;
    32             }
    33             if(tmp->right!=NULL){
    34                 q.push(tmp->right);
    35                 num2++;
    36             }
    37             
    38             if(level%2==0){
    39                 s.push(tmp);
    40             }
    41 
    42             if(num1==0){
    43                 if(level%2==0){
    44                     vv.clear();
    45                     while(!s.empty()){
    46                         vv.push_back(s.top()->val);
    47                         s.pop();
    48                     }
    49                 }
    50                 num1=num2;
    51                 num2=0;
    52                 v.push_back(vv);
    53                 vv.clear();
    54                 level++;
    55             }
    56         }
    57         
    58         return v;
    59     }
    60 };
  • 相关阅读:
    wifi 与 以太网 以及 修改网络查看网络
    git 与 gitHub 与 gitLab ,git常用5个命令
    花生壳
    诗词古文
    基金龙虎榜
    osm_mano安装
    db2快速删除大表数据(亲测可用)
    行列转换
    DB2表空间
    表分区,和分表区别
  • 原文地址:https://www.cnblogs.com/yy-1046741080/p/11647331.html
Copyright © 2020-2023  润新知