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();
            }
        }
        
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值