13ms C++ with DFS


  • 0
    T

    '''
    class Solution {
    public:
    int findBottomLeftValue(TreeNode* root) {
    pair<int,int> result = make_pair(0,root->val);
    digTree(root, 0, result);
    return result.second;
    }

    void digTree(TreeNode* root, int height, pair<int, int>& result) {
        if (!root) return;
        if (!root->left && !root->right) return;
        if (root->left && !root->left->left && !root->left->right){ //get to the left leaf
            if (height+1 > result.first) {
            result.first = height+1;
            result.second = root->left->val;
            }
        }
        if (!root->left && !root->right->left && !root->right->right){
            if (height+1 > result.first){
                result.first = height+1;
                result.second = root->right->val;
            }
        }
        digTree(root->left, height+1, result);
        digTree(root->right, height+1, result);
    }
    

    };
    '''
    This method uses DFS, the result will contain the max height and the value. We dig into the tree until meet a leaf. If the height is bigger then we replace the result with new one.


Log in to reply
 

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