Monday, April 8, 2013

Binary Tree Zigzag Level Order Traversal (C++ code)

LeetCode Binary Tree Zigzag Level Order Traversal, Sep 29 '12
难度4,出现频率3
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]
 
思路: 跟level order traversal一致,只是多一个flag记录每层正向还是逆向。

  1. vector<vector<int>> zigzagLevelOrder(TreeNode *root){  
  2.   vector<vector<int>> res;  
  3.   if(!root) return res;   
  4.   vector<int> level;  
  5.   queue<TreeNode *> myque;  
  6.   bool flag = true;   
  7.   TreeNode *last = root;  
  8.   myque.push(root);   
  9.   //main loop  
  10.   while(!myque.empty()){  
  11.    root = myque.front();  
  12.    myque.pop();  
  13.    if(root->left) myque.push(root->left);  
  14.    if(root->right) myque.push(root->right);  
  15.    if(flag == true)level.push_back(root->val);  
  16.    else level.insert(level.begin(), root->val);  
  17.    //when current level ends, store level in result, reset flag and level variable.  
  18.    if(root == last){  
  19.      res.push_back(level);  
  20.      level.clear();  
  21.      last = myque.back();  
  22.      flag = !flag;   
  23.    }   
  24.   }  
  25.   return res;   
  26. }   

No comments:

Post a Comment