1-pass DFS with O(1) space


  • 0
    int findBottomLeftValue(TreeNode* root) {
        int ret = 0;
        int maxL = -1;
        helper(root, ret, maxL, 0);
        return ret;
    }
    
    void helper(TreeNode* root, int& ret, int &maxL, int curL) {
        if (root == nullptr) {
            return;
        }
        if (root->left == nullptr && root->right == nullptr && curL > maxL) {
            maxL = curL;
            ret = root->val;
        }
        if (root->left != nullptr) {
            helper(root->left, ret, maxL, curL + 1);
        }
        if (root->right != nullptr) {
            helper(root->right, ret, maxL, curL + 1);
        }
    }
    

Log in to reply
 

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