本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

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]
]                                                                          本文地址

分析:首先肯定的是要对树进行层序遍历,但是相邻两层的元素遍历顺序是相反的,因此传统的非递归遍历方法用一个队列肯定是无法实现。我们用两个栈来实现,同一层元素都在同一个栈中,相邻的两层元素放在不同的栈中,比如第一层元素放在第一个栈,那么第二层就放在第二个栈,第三层就放在第三个栈......如果某一层元素是从左往右遍历的,那么这层元素的孩子节点入栈顺序就是先左孩子后右孩子,相反如果某一层元素是从右往左遍历的,入栈顺序就是先右孩子后左孩子。

 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         // IMPORTANT: Please reset any member data you declared, as
14         // the same Solution instance will be reused for each test case.
15         vector<vector<int> >res;
16         if(root == NULL)return res;
17         stack<TreeNode*> S,S2;
18         S.push(root);
19         bool isS = true;
20         vector<int>tmpres;
21         while(S.empty() == false || S2.empty() == false)
22         {
23             TreeNode *p;
24             if(isS)
25             {
26                 
27                 p = S.top();
28                 S.pop();
29                 tmpres.push_back(p->val);
30                 if(p->left)S2.push(p->left);
31                 if(p->right)S2.push(p->right);
32                 if(S.empty() == true)
33                 {
34                     res.push_back(tmpres);
35                     tmpres.clear();
36                     isS = false;
37                 }
38             }
39             else
40             {
41                 p = S2.top();
42                 S2.pop();
43                 tmpres.push_back(p->val);
44                 if(p->right)S.push(p->right);
45                 if(p->left)S.push(p->left);
46                 if(S2.empty() == true)
47                 {
48                     res.push_back(tmpres);
49                     tmpres.clear();
50                     isS = true;
51                 }
52             }
53         }
54         return res;
55     }
56 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3440512.html

posted @ 2013-11-24 21:21  tenos  阅读(998)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童