【Leetcode】【Medium】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]
]

 

解题思路:

按层遍历,建立两个栈,一个保存当前结点,一个按照Z型保存下一层结点。

使用一个bool变量来标注每次读取子节点的方向;

 

代码:

 1 /**
 2  * Definition for a binary tree node.
 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         vector<vector<int> > ret;
14         stack<TreeNode*> cur_layer;
15         stack<TreeNode*> next_layer;
16         cur_layer.push(root);
17         bool dirt = false;
18         
19         if (!root)
20             return ret;
21         
22         while (!cur_layer.empty()) {
23             vector<int> layer_val;
24             while (!cur_layer.empty()) {
25                 TreeNode* node = cur_layer.top();
26                 cur_layer.pop();
27                 layer_val.push_back(node->val);
28                 if (dirt) {
29                     if (node->right)
30                         next_layer.push(node->right);
31                     if (node->left)
32                         next_layer.push(node->left);
33                 } else {
34                     if (node->left)
35                         next_layer.push(node->left);
36                     if (node->right)
37                         next_layer.push(node->right);
38                 }
39             }
40             ret.push_back(layer_val);
41             swap(cur_layer, next_layer);
42             dirt = !dirt;
43         }
44         return ret;
45     }
46 };

 

posted @ 2015-05-21 09:54  胡潇  阅读(152)  评论(0编辑  收藏  举报