[leetcode] 103. 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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

解题思路:
本题是102. Binary Tree Level Order Traversal的变种题,都是层次化遍历,唯一的区别是102. Binary Tree Level Order Traversal遍历的时候每一层都是从左向右遍历,而本题遍历的时候是奇数行从左向右而偶数行从右向左,因此我们只需要设置一个标志位,其他思路基本相同。

代码如下:

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if(root == NULL) return ret;
        TreeNode* curr = root;
        queue<TreeNode*> stk;
        stk.push(root);
        bool leftToRight = true;
        
        while(!stk.empty())
        {
            int size = stk.size();
            vector<int> curLevel(size);
            for(int i = 0; i < size; ++i)
            {
                TreeNode* p = stk.front();
                stk.pop();
                int index = leftToRight ? i : size - i -1;
                curLevel[index] = p->val;
                if(p->left) stk.push(p->left);
                if(p->right) stk.push(p->right);
            }
            leftToRight = !leftToRight;
            ret.push_back(curLevel);
        }
        return ret;
    }
};

推荐阅读更多精彩内容