1. 程式人生 > >LeetCode Week 10

LeetCode Week 10

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).
在這裡插入圖片描述

solutions:

本題意是要求成Z字形輸出,順序為 左→右,下一層 右→左以此類推。

對於這道題採用佇列儲存遍歷的節點,每一層都按照左→右的順序,一層層的遍歷,當遇到偶數層時,將節點值反轉存進result。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if(!root)
            return result;
        queue<TreeNode *> q;
        q.push(root);
        int dep = 1;  // level
        while(!q.empty()) {
            int size = q.size();
            vector<int> level;
            for(int i = 0; i < size; i++) {
                TreeNode *node = q.front();
                q.pop();
                level.push_back(node->val);
                if(node->left)
                    q.push(node->left);
                if(node->right)
                    q.push(node->right);
            }
            if(dep % 2 == 0) {
                reverse(level.begin(), level.end());
            }
            dep++;
            result.push_back(level);
        }
        return result;
    }
private:
    vector<vector<int>> result;
};

在這裡插入圖片描述