C++ Solution for Find Leaves of Binary Tree


  • 0
    G
    class Solution {
    public:
        vector<vector<int>> findLeaves(TreeNode* root) {
            vector<vector<int> > result;
            if(root==NULL)  return result;
            result.push_back(vector<int>());
            int a=level(root,result);
            return  result;
        }
        
        int level(TreeNode* root,vector<vector<int>> &result){
            if(root==NULL)  return 0;
            if(root->left==NULL&&root->right==NULL){
                result[0].push_back(root->val);
                return 1;
            }
            int a=max(level(root->left,result),level(root->right,result))+1;
            if(a>result.size()) result.push_back(vector<int>());
            result[a-1].push_back(root->val);
            return a;
        }
        
    };

Log in to reply
 

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