java 二叉树的最低共同祖先

Posted

tags:

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

// This code assumes both nodes exist

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 ? left : right;
}

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