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

结点:

class TreeNode {
public:
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {} 
};

分析:

基本题,5分钟,1次过。

解法:

class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: A list of lists of integer include 
     *          the zigzag level order traversal of its nodes' values 
     */
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
        // write your code here
        vector<vector<int> > res;
        if (root == NULL) {
            return res;
        }
        queue<TreeNode*> Q;
        Q.push(root);
        bool needReverse = false;
        while (!Q.empty() ) {
            int size = Q.size();
            vector<int> level;
            for (int i = 0; i < size; i++) {
                TreeNode* temp = Q.front();
                Q.pop();
                level.push_back(temp->val);
                if (temp->left != NULL) {
                    Q.push(temp->left);
                }
                if (temp->right != NULL) {
                    Q.push(temp->right);
                }
            }
            if (needReverse) {
                reverse(level.begin(), level.end() );
            }
            res.push_back(level);
            needReverse = !needReverse;
        }
        return res;
    }
};

results matching ""

    No results matching ""