File tree Expand file tree Collapse file tree 1 file changed +31
-4
lines changed Expand file tree Collapse file tree 1 file changed +31
-4
lines changed Original file line number Diff line number Diff line change @@ -561,12 +561,39 @@ public class TreeSolvingUtil {
561561 System . out. println();
562562 }
563563
564- /**
565- * 6、二叉树zigzag打印
566- */
567-
568564 /**
569565 * 7、二叉树,给定量给节点,求这两个节点的最近公共祖先
566+ *
567+ * @param root 根节点
568+ * @param p p节点
569+ * @param q q节点
570+ * @return
570571 */
572+ public TreeNode lowestCommonAncestor (TreeNode root , TreeNode p , TreeNode q ) {
573+
574+ // 如果树为空,直接返回null;
575+ // 如果 p和q中有等于 root的,那么它们的最近公共祖先即为root(一个节点也可以是它自己的祖先)
576+ if (root == null || p == root || q == root) {
577+ return root;
578+ }
579+
580+
581+ // 递归遍历左子树,只要在左子树中找到了p或q,则先找到谁就返回谁
582+ TreeNode left = lowestCommonAncestor(root. left, p, q);
583+ // 递归遍历右子树,只要在右子树中找到了p或q,则先找到谁就返回谁
584+ TreeNode right = lowestCommonAncestor(root. right, p, q);
585+
586+
587+ // left和 right均不为空时,说明 p、q节点分别在 root异侧, 最近公共祖先即为 root
588+ if (left != null && right != null ) {
589+ return root;
590+ }
591+
592+ // 如果在左子树中p和q都找不到,则p和q一定都在右子树中,右子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
593+ // 否则,如果 left不为空,在左子树中有找到节点(p或q),这时候要再判断一下右子树中的情况,
594+ // 如果在右子树中,p和q都找不到,则 p和q一定都在左子树中,左子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
595+ return left == null ? right : left;
596+ }
597+
571598}
572599```
You can’t perform that action at this time.
0 commit comments