File tree Expand file tree Collapse file tree 4 files changed +211
-99
lines changed
data-structure-algorithms/soultion Expand file tree Collapse file tree 4 files changed +211
-99
lines changed Original file line number Diff line number Diff line change 1- Subproject commit 73649b860108b81cbcc8f505c077d5d287e3190d
1+ Subproject commit e02f59de5d2afd19f5f9bde3a84cd808a20b3094
Original file line number Diff line number Diff line change @@ -1574,32 +1574,30 @@ class Solution {
15741574
15751575
15761576```java
1577- public class Solution {
1578- public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
1579- // 如果当前节点为空,则返回null
1580- if (root == null) {
1581- return null;
1582- }
1583- // 如果当前节点是p或q,则返回当前节点
1584- if (root == p || root == q) {
1585- return root;
1586- }
1587- // 递归地在左子树中查找p和q
1588- TreeNode left = lowestCommonAncestor(root.left, p, q);
1589- // 递归地在右子树中查找p和q
1590- TreeNode right = lowestCommonAncestor(root.right, p, q);
1591-
1592- // 根据left和right的值来判断最近公共祖先
1593- if (left != null && right != null) {
1594- // p和q分别位于左右子树中,当前节点是最近公共祖先
1595- return root;
1596- } else if (left != null) {
1597- // p和q都在左子树中,返回左子树的结果
1598- return left;
1599- } else {
1600- // p和q都在右子树中,返回右子树的结果
1601- return right;
1602- }
1577+ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
1578+ // 如果当前节点为空,则返回null
1579+ if (root == null) {
1580+ return null;
1581+ }
1582+ // 如果当前节点是p或q,则返回当前节点
1583+ if (root == p || root == q) {
1584+ return root;
1585+ }
1586+ // 递归地在左子树中查找p和q
1587+ TreeNode left = lowestCommonAncestor(root.left, p, q);
1588+ // 递归地在右子树中查找p和q
1589+ TreeNode right = lowestCommonAncestor(root.right, p, q);
1590+
1591+ // 根据left和right的值来判断最近公共祖先
1592+ if (left != null && right != null) {
1593+ // p和q分别位于左右子树中,当前节点是最近公共祖先
1594+ return root;
1595+ } else if (left != null) {
1596+ // p和q都在左子树中,返回左子树的结果
1597+ return left;
1598+ } else {
1599+ // p和q都在右子树中,返回右子树的结果
1600+ return right;
16031601 }
16041602}
16051603```
You can’t perform that action at this time.
0 commit comments