二叉树的最近公共祖先 (Lowest Common Ancestor of a Binary Tree)

 

思路:

// @Title: 二叉树的最近公共祖先 (Lowest Common Ancestor of a Binary Tree)
// @Author: qisiii
// @Date: 2024-09-16 17:06:58
// @Runtime: 7 ms
// @Memory: 43.8 MB
// @comment: 
// @flag: 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null||root==q||root==p){
            return root;
        }
        //在左子树能否找到
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left==null&&right==null){
            return null;
        //如果左边找不到,那么就代表两个节点一定在右子树,此时最先遇到的节点就是祖先
        }else if(left==null){
            return right;
        }else if(right==null){
            return left;
        }else{
            return root;
        }
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18