[Leetcode] Binary Tree Zigzag Level Order Traversal

Binary Tree Zigzag Level Order Traversal 题解

题目来源:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/


Description

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).

Example

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]
]

Solution

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if (root == NULL)
            return res;
        queue<TreeNode*> q;
        q.push(root);
        q.push(NULL);
        vector<int> level;
        bool isReverse = false;
        while (!q.empty()) {
            TreeNode *node = q.front();
            q.pop();
            if (node) {
                level.push_back(node -> val);
                if (node -> left)
                    q.push(node -> left);
                if (node -> right)
                    q.push(node -> right);
            } else {
                if (isReverse)
                    reverse(level.begin(), level.end());
                res.push_back(level);
                isReverse = !isReverse;
                level.clear();
                if (!q.empty())
                    q.push(NULL);
            }
        }
        return res;
    }
};

解题描述

这道题题意是对二叉树进行层次遍历,但是要求相邻两层之间的遍历顺序相反。上面的解法是使用一个标记布尔值isReverse,在每一层遍历结束的时候对其取反,根据布尔值来决定层次遍历的数据level在加入结果res之前是否需要进行反转。

当然,反转的开销还是相对较大,评论区给出了一种使用下标处理来进行的层次结果增长方向的控制的方法,相对来说开销较小:


class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
        vector<vector<int> > res;
        if (!root)
            return res;
        queue<TreeNode*> q;
        q.push(root);
        bool isReverse = false;
        while (!q.empty()) {
            TreeNode* node = q.front();
            int size = q.size();
            res.push_back(vector<int>(size));
            for (int i = 0; i < size; i++) {
                int index = isReverse ? size - 1 - i : i;
                TreeNode *node = q.front();
                q.pop();
                res.back()[index] = node -> val;
                if (node -> left)
                    q.push(node -> left);
                if (node -> right)
                    q.push(node -> right);
            }
            isReverse = !isReverse;
        }
        return res;
    }
};

posted @ 2018-01-30 16:19  言何午  阅读(93)  评论(0编辑  收藏  举报