4ms C++ solution


  • 0
    P
    class Solution {
        int deep(TreeNode *rt){          //compute the depth of the tree
            if(!rt) return 0;
            return max(deep(rt->left),deep(rt->right))+1;
        }
        void mapping(TreeNode *rt,vector<vector<int> > &rst,int lev){  //use lev to denote the corrent level of the node
            if(!rt) return;
            rst[lev].push_back(rt->val);
            mapping(rt->left,rst,lev+1);
            mapping(rt->right,rst,lev+1);
            return;
        }                                                        
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            int height = deep(root);
            vector<vector<int> > rst(height);
            mapping(root,rst,0);
            return rst;
        }
    };

Log in to reply
 

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