leetcode 103. 二叉树的锯齿形层次遍历

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

[
  [3],
  [20,9],
  [15,7]
]
 1 class Solution {
 2 public:
 3     vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
 4         stack<TreeNode*> s;
 5         vector<vector<int>> ans;
 6         s.push(root);
 7         if(root == NULL) return ans;
 8         vector<int> tt;
 9         tt.push_back(root->val);
10         ans.push_back(tt); //把第一行加入答案中
11         bool flag = true;
12         while(!s.empty()){
13             vector<int> t;
14             TreeNode* temp;
15             stack<TreeNode*> st;
16             bool f = false; //标志一次遍历是否有值压入
17             
18             if(flag){ //从右到左遍历
19                 while(!s.empty()){
20                     temp = s.top();
21                     s.pop();
22                     if(temp->right){
23                         st.push(temp->right);
24                         t.push_back(temp->right->val);
25                         f = true;
26                     } 
27                     if(temp->left){
28                         st.push(temp->left);
29                         t.push_back(temp->left->val);
30                         f = true;
31                     } 
32                 }
33                 flag = false;
34                 s = st;
35             }else{//从左到右遍历
36                 while(!s.empty()){
37                     TreeNode* temp = s.top();
38                     s.pop();
39                     if(temp->left){
40                         st.push(temp->left);
41                         t.push_back(temp->left->val);
42                         f = true;
43                     } 
44                     if(temp->right){
45                         st.push(temp->right);
46                         t.push_back(temp->right->val);
47                         f = true;
48                     } 
49                 }
50                 flag = true;
51                 s = st;
52             }
53              if(f) ans.push_back(t);
54         }
55         return ans;
56     }
57 };

猜你喜欢

转载自www.cnblogs.com/mr-stn/p/8978174.html