码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Zigzag Level Order Traversal

时间:2014-05-15 23:18:46      阅读:515      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   c++   二叉树   

原题:


题目解析:这个问题的实质是要我们按成访问二叉树的结点,并返回每层访问的结果,这里要求走Z字,其实就是一行正向一行反向。

/*
  the kernel idea is visit a binary search tree in level and 
  the additional work we have to label the end of one level.
*/
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {

	vector<vector<int> > re;
	if(root == NULL)
		return re;

	queue<TreeNode*> visit;
	vector<int> level;

	visit.push(root);
	//NULL stands for the end of this level
	visit.push(NULL);
	//in store every level result, we are asked to change direction.
	bool reback = false;
	while (!visit.empty())
	{
		TreeNode* cur = visit.front();
		
		visit.pop();
		if(cur != NULL){
			if(cur->left)
				visit.push(cur->left);
			if(cur->right)
				visit.push(cur->right);
			level.push_back(cur->val);
		}

		else
		{
			if(reback)
			{
				vector<int> rlevel(level.rbegin(),level.rend());
				re.push_back(rlevel);
				
			}
			else
			re.push_back(level);

			//remember to clear this level.
			level.clear();
			reback = !reback;

			if(!visit.empty())
				visit.push(NULL);
		}
		
	}
	return re;
}




Binary Tree Zigzag Level Order Traversal,布布扣,bubuko.com

Binary Tree Zigzag Level Order Traversal

标签:algorithm   leetcode   c++   二叉树   

原文地址:http://blog.csdn.net/shiquxinkong/article/details/25904083

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!