DFS solution O(n) time O(1) time


  • 0
    M
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void _findBottomLeftValue(TreeNode* root, int level, int& max, int& val)
        {
            if(root == NULL)
                return;
            
            if(max < level)
            {
                val = root->val;
                max = level;
            }
            
            _findBottomLeftValue(root->left,level+1,max,val);
            _findBottomLeftValue(root->right,level+1,max,val);
            
        }
        
        int findBottomLeftValue(TreeNode* root) {
            
            int level = 1;
            int max =  0;
            int val = 0;
            _findBottomLeftValue(root,level,max,val);
            return val;
            
        }
    };```

Log in to reply
 

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