c++ a simple method


  • 0
    H
    class Solution {
    public:
        int depth(TreeNode* root) {
            if(!root) return 0;
            return 1 + max(depth(root->left), depth(root->right));
        }
        void dfs(TreeNode* root, int level, vector<vector<int> > &ans) {
            if(!root) return;
            ans[level].push_back(root->val);
            dfs(root->left, level+1, ans);
            dfs(root->right, level+1, ans);
        }
        vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
            int n = depth(root);
            vector<vector<int> > ans(n);
            dfs(root, 0, ans);
            for(int i = 1; i < n; i = i + 2)
                reverse(ans[i].begin(), ans[i].end());
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.