标签:
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