C++ solution using dfs


  • 0
    G
    class Solution {
    public:
        
        using TP= pair<TreeNode*,int>;
        
        TP findBottom(TreeNode *root, int level){
            if(root == nullptr){
                return {nullptr,level};
            }
            
            TP left = findBottom(root->left,level + 1);
            TP right = findBottom(root->right,level + 1);
            
            if(left.first == nullptr && right.first == nullptr){
                return {root,level};
            }
            else if(left.first == nullptr){
                    return right; 
            }
            else if(right.first == nullptr){
                return left;
            }
            
            if(left.second >= right.second){
                return left;
            }
    
            return right;
        }
        
        int findBottomLeftValue(TreeNode* root) {
            TP res = findBottom(root,0);
            return res.first->val;
        }
    };
    
    

Log in to reply
 

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