103. 二叉树的锯齿形层序遍历

102 阅读1分钟

c++

class Solution {
public:
    void zigzagLevelOrderImpl(TreeNode *root, vector<vector<int>> &ans, int deepth) {
        if (!root) return ;
        if (ans.size() == deepth) ans.push_back(vector<int> ());
        ans[deepth].push_back(root->val);
        zigzagLevelOrderImpl(root->left, ans, deepth + 1);
        zigzagLevelOrderImpl(root->right, ans, deepth + 1);
        return ;
    }
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if (!root) return vector<vector<int>> ();
        vector<vector<int>> ans;
        zigzagLevelOrderImpl(root, ans, 0);
        for (int i = 0; i < ans.size(); i++) {
            if (i % 2) reverse(ans[i].begin(), ans[i].end());
        }
        return ans;
    }
};

js

function zigzagLevelOrderImpl(root, ans, deepth) {
    if (!root) return ;
    if (ans.length == deepth) ans.push([]);
    ans[deepth].push(root.val);
    zigzagLevelOrderImpl(root.left, ans, deepth + 1);
    zigzagLevelOrderImpl(root.right, ans, deepth + 1);
    return ;
}

var zigzagLevelOrder = function(root) {
    if (!root) return [];
    let ans = [];
    zigzagLevelOrderImpl(root, ans, 0);
    for (var i = 0; i < ans.length; i++) {
        if (i % 2) ans[i].reverse();
    }
    return ans;
};