1. 程式人生 > >#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

https://leetcode.com/problems/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]
]

程式碼:

/**
 * 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) {
        vector<vector<int> > ans;
        if(!root) return ans;
        level(root, ans, 1);
        for(int i = 0; i < ans.size(); i ++) {
            if(i % 2) {
                for(int j = 0; j < ans[i].size() / 2; j ++)
                    swap(ans[i][j], ans[i][ans[i].size() - j - 1]);
            }
        }
        return ans;
    }
    void level(TreeNode* root, vector<vector<int> >& ans, int depth) {
        vector<int> v;
        if(depth > ans.size()) {
            ans.push_back(v);
            v.clear();
        }
        ans[depth - 1].push_back(root -> val);
        if(root -> left)
            level(root -> left, ans, depth + 1);
        if(root -> right)
            level(root -> right, ans, depth + 1);
    }
};