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

157 阅读1分钟

算法记录

LeetCode 题目:

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


说明

一、题目

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

二、分析

  • 如果一个节点为此两个节点的最近公共祖先,那么必定能在该节点的左右子树中存在。
  • 利用这一性质进行递归查找,只要找到任意节点就返回。
  • 找不到就继续向下查找,往左右子树中深入时都拿到了存在信息,就直接返回该节点即可。
/**
 * 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) {
        return find(root, p, q);
    }

    public TreeNode find(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        if(root == p || root == q) return root;
        TreeNode l = find(root.left, p, q);
        TreeNode r = find(root.right, p, q);
        if(l != null && r != null) return root;
        if(l != null) return l;
        return r;
    }
}

总结

熟悉二叉树的递归遍历查找。