标签:des style blog http color os io strong for
LeetCode: Binary Tree Zigzag Level Order Traversal
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] ]
地址:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
算法:变着花样来遍历一颗树,二叉树都快被玩坏了。还是在二叉树层次遍历的结果上进行处理。代码:
1 /**
2 * Definition for binary tree
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 if(!root) return vector<vector<int> >();
14 queue<TreeNode *> que;
15 que.push(root);
16 int push_num = 1;
17 int pop_num = 0;
18 vector<vector<int> > result;
19 vector<int> temp;
20 int last = 1;
21 while(!que.empty()){
22 TreeNode *pop_node = que.front();
23 temp.push_back(pop_node->val);
24 que.pop();
25 ++pop_num;
26 if(pop_node->left){
27 que.push(pop_node->left);
28 ++push_num;
29 }
30 if(pop_node->right){
31 que.push(pop_node->right);
32 ++push_num;
33 }
34 if(pop_num == last){
35 result.push_back(temp);
36 temp.clear();
37 last = push_num;
38 }
39 }
40 for(int i = 1; i < result.size(); i += 2){
41 int len = result[i].size();
42 int half_len = len / 2;
43 for(int j = 0; j < half_len; ++j){
44 int t = result[i][j];
45 result[i][j] = result[i][len-j-1];
46 result[i][len-j-1] = t;
47 }
48 }
49 return result;
50 }
51 };
LeetCode: Binary Tree Zigzag Level Order Traversal
标签:des style blog http color os io strong for
原文地址:http://www.cnblogs.com/boostable/p/leetcode_binary_tree_zigzag_level_order_traversal.html