LowestCommonAncestor

  • 2022-12-14
  • 浏览 (645)

LowestCommonAncestor.java 源码

package algorithm.recursion;

/**
 * @author roseduan
 * @time 2020/9/24 8:45 下午
 * @description 二叉树的最近公共祖先
 */
public class LowestCommonAncestor {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        }
        return left == null ? right : left;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}

你可能感兴趣的文章

BstLowestCommonAncestor

ClimeStairs

Combinations

0  赞