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

Binary Tree Zigzag Level Order Traversal

时间:2015-03-16 16:34:14      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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]
]
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

vector<vector<int> > levelOrder(TreeNode *root) {
	queue<pair<TreeNode*,int> >  BFS_Queue;
	vector<int> LevelVal;
	vector<vector<int> > Result;

	if (root == NULL)
		return Result;
	BFS_Queue.push(make_pair(root,0));
	int Curlevel = 0;
	while (!BFS_Queue.empty())
	{
		TreeNode* Curnode = BFS_Queue.front().first;
		if (BFS_Queue.front().second != Curlevel)
		{
			Result.push_back(LevelVal);
			LevelVal.clear();
			Curlevel = BFS_Queue.front().second;
		}
		if (BFS_Queue.front().second%2==0)
			LevelVal.push_back(Curnode->val);
		else
			LevelVal.insert(LevelVal.begin(),Curnode->val);
		BFS_Queue.pop();
		if (Curnode->left)
			BFS_Queue.push(make_pair(Curnode->left, Curlevel + 1));
		if (Curnode->right)
			BFS_Queue.push(make_pair(Curnode->right, Curlevel + 1));
	}
	Result.push_back(LevelVal);
	return Result;
}


 

 

Binary Tree Zigzag Level Order Traversal

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/44306553

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