Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f3e9651

Browse files
🐱(recursion): 236. 二叉树的最近公共祖先
补充 golang
1 parent 0fa1ef9 commit f3e9651

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎docs/data-structure/tree/recursion/README.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,6 +729,41 @@ class Solution:
729729
return root
730730
```
731731

732+
#### **Go**
733+
734+
```go
735+
/**
736+
* Definition for TreeNode.
737+
* type TreeNode struct {
738+
* Val int
739+
* Left *ListNode
740+
* Right *ListNode
741+
* }
742+
*/
743+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
744+
if root == nil || root == p || root == q {
745+
return root
746+
}
747+
748+
// 寻找左子树
749+
left := lowestCommonAncestor(root.Left, p, q)
750+
// 寻找右子树
751+
right := lowestCommonAncestor(root.Right, p, q)
752+
753+
if left == nil && right == nil {
754+
return nil
755+
}
756+
if left == nil {
757+
return right
758+
}
759+
if right == nil {
760+
return left
761+
}
762+
763+
return root
764+
}
765+
```
766+
732767
<!-- tabs:end -->
733768

734769
## 337. 打家劫舍 III

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /