LeetCode #1123

Lowest Common Ancestor of Deepest Leaves

1개의 풀이 · C++

문제 원문 보기 ↗

SOLUTION INFO

C++ · main.cpp

main.cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* lcaDeepestLeaves(TreeNode* root) {
        return dfs(root).first;
    }
    pair<TreeNode*, int> dfs(TreeNode* x) {
        if(x == nullptr) return {nullptr, 0};
        auto L = dfs(x->left);
        auto R = dfs(x->right);
        if(L.second > R.second) return {L.first, L.second + 1};
        if(L.second < R.second) return {R.first, R.second + 1};
        return {x, L.second + 1};
    };
};

SOLUTION DESCRIPTION

풀이 설명

등록된 풀이 설명이 없습니다.