LeetCode 103. Binary Tree Zigzag Level Order Traversal
思路:维护两个stack<TreeNode*> stk1, stk2,stk1存放当前层的节点,stk2存放下一层的节点。
bool right表示下一层的顺序,如果为True则下一层为从右到左,因为stk2是stack,所以stk2先存cur->left,然后存cur->right。
当stk1为空,即当前层的节点遍历完时,将stk1、stk2之间swap,即永远对stk1进行处理,并把当前层生成的vector level压入最终的vector res中,注意level要clear且 right要取反
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 vector<vector<int>> res; 14 if(!root) return res; 15 16 vector<int> level; 17 stack<TreeNode* > stk1, stk2; 18 19 stk1.push(root); 20 bool right = true; 21 22 while( !stk1.empty() ){ 23 TreeNode* cur = stk1.top(); 24 stk1.pop(); 25 level.push_back(cur->val); 26 27 if(right){ 28 if(cur->left) stk2.push(cur->left); 29 if(cur->right) stk2.push(cur->right); 30 } 31 else{ 32 if(cur->right) stk2.push(cur->right); 33 if(cur->left) stk2.push(cur->left); 34 } 35 36 if(stk1.empty()){ 37 res.push_back(level); 38 level.clear(); 39 stk1.swap(stk2); 40 right = !right; 41 } 42 } 43 44 return res; 45 46 } 47 };