6ms avoiding reversal of vector (c++)


  • 0
    C

    Calculating the height of the tree to avoid reversing the vector.

    class Solution {
    public:
        void levelOrder(TreeNode* root,vector<vector<int>> &ans,  int height){
            if(root == NULL){
                return;
            }
            ans[height].push_back(root->val);
            levelOrder(root->left, ans, height-1);
            levelOrder(root->right, ans, height-1);
        }
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> ans;
            int height = heightTree(root);
            for(int i =0;i<height;i++){
                ans.push_back(vector<int>());
            }
            levelOrder(root, ans, height-1);
            return ans;
        }
        int heightTree(TreeNode* root){
            int height=0;
            if(root==NULL){
                return 0;
            }
            height = 1 + max(heightTree(root->left),heightTree(root->right)); 
            return height;
        }
    };
    

Log in to reply
 

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