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] ]
题目的意思很直白,层序遍历整个树,但是第一层正序输出,第二层反序输出,第三层正序输出,以此类推。做法有两种:一、仍然采用level-travel,只是引入一个标记,判断是否反转得到的数列; 二、考虑到stack的特点,利用stack FILO的特点来直接输出;两种方法都贴出来
利用stack的:
class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { bool isRe = false; vector<int> a; stack<TreeNode *> s1, s2; if (root == NULL) return ret; s1.push(root); while (!s1.empty()){ TreeNode *tmp = s1.top(); s1.pop(); a.push_back(tmp->val); if (isRe){ if (tmp->right) s2.push(tmp->right); if (tmp->left) s2.push(tmp->left); } else{ if (tmp->left) s2.push(tmp->left); if (tmp->right) s2.push(tmp->right); } if (s1.empty()){ ret.push_back(a); isRe = !isRe; swap(s1, s2); a.clear(); } } return ret; } private: vector<vector<int>> ret; };
class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int>> ret; queue<TreeNode *> current, next; //利用两个队列的交替来区分每一层 bool isRe = false; vector<int> v; if (root == NULL) return ret; current.push(root); while (!current.empty()){ TreeNode *tmp = current.front(); current.pop(); v.push_back(tmp->val); if (tmp->left) next.push(tmp->left); if (tmp->right) next.push(tmp->right); if(current.empty()){ if (isRe){ reverse(v.begin(), v.end()); } ret.push_back(v); swap(current,next); isRe = !isRe; v.clear(); } } } };
LeetCode :: Binary Tree Zigzag Level Order Traversal [tree, BFS]
原文地址:http://blog.csdn.net/u013195320/article/details/37994615