当前位置:网站首页>Leetcode 236. 二叉树的最近公共祖先

Leetcode 236. 二叉树的最近公共祖先

2022-08-09 22:05:00 LuZhouShiLi

Leetcode 236. 二叉树的最近公共祖先

题目

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

思路

  • 递归出口

    • 当越过叶子节点,直接返回null
    • 当root等于p,q,直接返回root
  • 递归工作

    • 递归左子树
    • 递归右子树
    • 判断左子树和右子树是否为空
  • 返回值

    • 左右子树都不为空,说明左右子树都不包含p,q,返回null
    • 当左右子树同时不为空,直接返回root
    • 当左右子树有一个为空,另一个不为空,返回不为空的那个

代码

/** * 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 {
    
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    
        if(root == nullptr || root == p || root == q)
        {
    
            return root;
        }

        // 递归左子树
        TreeNode *l = lowestCommonAncestor(root->left,p,q);

        // 递归右子树
        TreeNode *r = lowestCommonAncestor(root->right,p,q);

        if(l == nullptr)
        {
    
            // 左子树为空 p q 在右子树中
            return r;
        }

        if(r == nullptr)
        {
    
            return l;// 右子树为空 pq 在左子树中
        }

        return root;
    }
};

原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_44653420/article/details/126248807