首页 > 代码库 > LeetCode :: Binary Tree Zigzag Level Order Traversal [tree, BFS]
LeetCode :: Binary Tree Zigzag Level Order Traversal [tree, BFS]
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; };
利用queue的,这里由于引入了swap,所以可以复用同一个代码流程,代码会短一些;
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]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。