simple DFS C++ solution


  • 0
    N
    /**
     * 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 {
    private:
        void dfs(TreeNode* root, int dep, pair<int, int>& ans){
            if (!root) return;
            if (dep > ans.second) ans = make_pair(root->val, dep);
            dfs(root->left, dep + 1, ans);
            dfs(root->right, dep + 1, ans);
        }
    public:
        int findBottomLeftValue(TreeNode* root) {
            pair<int, int> ans(0, 0);
            dfs(root, 1, ans);
            return ans.first;
        }
    };
    

Log in to reply
 

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