标签:leetcode 二叉树 bfs 层序遍历 queue
problem:
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] ]
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
thinking:
(1)层序遍历采用BFS广度优先搜索,借用队列queue
(2)要实现Z字形 层序遍历,要采用一个BOOL 值标记先访问左还是右孩子的顺序,还要借助两个queue,
其中一个用于输出VAL值,另外一个要借助stack实现翻转,保存访问下一层的孩子节点
code:
class Solution { private: vector<vector<int> > ret; public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { ret.clear(); if(root==NULL) return ret; queue<TreeNode *> tmp_queue; tmp_queue.push(root); level_order(tmp_queue,false); return ret; } protected: void level_order(queue<TreeNode *> &queue1,bool flag) { if(queue1.empty()) return; vector<int> array; queue<TreeNode *> queue0=queue1; queue<TreeNode *> queue2=queue_reverse(queue1); queue<TreeNode *> queue3; while(!queue0.empty()) //打印结点 { TreeNode *tmp=queue0.front(); queue0.pop(); array.push_back(tmp->val); } while(!queue2.empty()) //访问孩子节点 { TreeNode *tmp=queue2.front(); queue2.pop(); if(flag) //flag规定先访问左孩子还是右孩子 { if(tmp->left!=NULL) queue3.push(tmp->left); if(tmp->right!=NULL) queue3.push(tmp->right); } else { if(tmp->right!=NULL) queue3.push(tmp->right); if(tmp->left!=NULL) queue3.push(tmp->left); } } flag=!flag; ret.push_back(array); level_order(queue3,flag); //递归访问下一层 } queue<TreeNode *> queue_reverse(queue<TreeNode *> &_queue) //借助stack实现queue翻转 { stack<TreeNode *> _stack; queue<TreeNode *> ret_queue; while(!_queue.empty()) { TreeNode *tmp=_queue.front(); _stack.push(tmp); _queue.pop(); } while(!_stack.empty()) { TreeNode *tmp=_stack.top(); ret_queue.push(tmp); _stack.pop(); } return ret_queue; } };
leetcode || 103、Binary Tree Zigzag Level Order Traversal
标签:leetcode 二叉树 bfs 层序遍历 queue
原文地址:http://blog.csdn.net/hustyangju/article/details/45165817