2019年11月12日 星期二

Binary Tree Zigzag Level Order Traversal


Binary Tree Zigzag Level Order Traversal

  • Lintcode : 71 / Leetcode : 103
  • Level : Medium

Problem

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
Example 1:

Input:{1,2,3}
Output:[[1],[3,2]]
Explanation:
    1
   / \
  2   3
it will be serialized {1,2,3}
Example 2:

Input:{3,9,20,#,#,15,7}
Output:[[3],[20,9],[15,7]]
Explanation:
    3
   / \
  9  20
    /  \
   15   7
it will be serialized {3,9,20,#,#,15,7}

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n)
space: O(n)

Answer

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
        int row = 1;
        vector<vector<int>> ans;
        if (root == nullptr) return ans;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int s = q.size();
            vector<int> res;
            for (int i = 0; i < s; i++) {
                TreeNode* p = q.front(); q.pop();
                res.push_back(p -> val);
                if (p -> left) q.push(p -> left);
                if (p -> right) q.push(p -> right);
            }
            if (row % 2 == 0) {
                reverse(res.begin(), res.end());
            } 
            ans.push_back(res);
            row++;
        }
        return ans;
    }
};
tags: BFS

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...