题解 | #在二叉树中找到两个节点的最近公共祖先#

在二叉树中找到两个节点的最近公共祖先

https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116

class Solution {
  private:
    TreeNode* Preoder(TreeNode* root, int o1, int o2) {
        if (root == nullptr || root->val == o1 || root->val == o2) {
            return root;
        }

        TreeNode* leftResult = Preoder(root->left, o1, o2);
        TreeNode* rightResult = Preoder(root->right, o1, o2);
        if (leftResult != nullptr && rightResult != nullptr) {
            return root;
        } else if (leftResult != nullptr && rightResult == nullptr) {
            return leftResult;
        } else if (leftResult == nullptr && rightResult != nullptr) {
            return rightResult;
        }
        return nullptr;
    }

  public:
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        // 本题保证非空
        TreeNode* result = Preoder(root, o1, o2);
        return result->val;
        }
};

全部评论

相关推荐

爱读书的放鸽子能手很...:刷个两端实习,冲春招,流水线什么时候不能去
我的秋招日记
点赞 评论 收藏
分享
09-14 17:23
门头沟学院
故事和酒66:所以说副业很重要,程序员干到40岁,再怎么也赚300万了,吃吃利息也够活下去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务