leetcode 103. Zigzag Hierarchical Traversal of Binary Trees

Given a binary tree, return a zigzag hierarchical traversal of its node values. (That is, the next layer is traversed from left to right, and then from right to left, and so on, alternating between layers).

For example:
given a binary tree  [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

Return the zigzag level traversal as follows:

[
  [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         boolflag = true ;
 12          while (! s.empty()){
 13              vector< int > t;
 14              TreeNode* temp;
 15              stack<TreeNode*> st;
 16              bool f = false ; // flag whether there is value pressure in one traversal Enter 
17              
18              if (flag){ // traverse 19 from right to left 
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 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325111730&siteId=291194637