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 };

 

posted @ 2019-10-10 13:02  B_luePhantom  阅读(96)  评论(0编辑  收藏  举报