二叉树进阶题------最近公共祖先

Posted 小写丶H

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树进阶题------最近公共祖先相关的知识,希望对你有一定的参考价值。

最近公共祖先


二叉树进阶题

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。(最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”)
p 和 q 均存在于给定的二叉树中。

思路

自上而下的深度遍历DFS。理解下面这个图,然后看代码注释。

代码

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) 
		//空树 是没有公共祖先的
        if(root == null) return null;
        //root等于p,q中的某一个 ,返回给leftTree/rightTree
        if(root == p || root == q) 
            return root;
        
        //遍历左子树
        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);
        //遍历右子树
        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);
        //当左右子树都不为空,那么公共祖先为root
        if(leftTree != null && rightTree != null) 
            return root;
        
        //leftTree为空,rightTree不为空,那么祖先就是rightTree
        if(leftTree == null && rightTree != null) 
            return rightTree;
        
        //leftTree不为空,rightTree为空,那么祖先就是leftTree
        if(leftTree != null && rightTree == null) 
            return leftTree;
        
        //leftTree为空,rightTree为空,那么祖先就是没有公共祖先(理论上可以不需要这个判断,因为p,q存在于给定子树中)
        if(leftTree == null && rightTree == null) 
            return null;
        
        return null;
    

以上是关于二叉树进阶题------最近公共祖先的主要内容,如果未能解决你的问题,请参考以下文章

二叉树经典题之二叉树最近公共祖先(LeetCode)

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

236. 二叉树的最近公共祖先[中等]

236-二叉树的最近公共祖先

经典面试题--二叉树的最近公共祖先

LeetCode Java刷题笔记—236. 二叉树的最近公共祖先