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


原文地址:https://www.cnblogs.com/zfyouxi/p/5080505.html