My simple solution without using queue


  • 0
    Y
    class Solution {
    public:
        vector<vector<int> > ret;
        void dfs(TreeNode *node, int level){
            if (node == NULL) return;
            if (ret.size() <= level) ret.resize(level+1);
            ret[level].push_back(node->val);
            dfs(node->left, level+1);
            dfs(node->right, level+1);
        }
        vector<vector<int> > levelOrder(TreeNode *root) {
            dfs(root, 0);
            return ret;
        }
    };
    

    This is done by the property of pre-order traversal.


  • 0
    D

    FYI, resize is O(n) if reallocation happens


Log in to reply
 

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