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 7e565c5

Browse files
feature: add go solution for leetcode 0235
1 parent cfe2b0d commit 7e565c5

File tree

2 files changed

+58
-3
lines changed

2 files changed

+58
-3
lines changed

‎solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README.md‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,37 @@ class Solution {
100100
}
101101
```
102102

103-
### **...**
104-
```
103+
### **Go**
104+
105+
```go
106+
/**
107+
* Definition for TreeNode.
108+
* type TreeNode struct {
109+
* Val int
110+
* Left *ListNode
111+
* Right *ListNode
112+
* }
113+
*/
114+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
115+
if root == nil {
116+
return nil
117+
}
105118

119+
for root != nil {
120+
//如果p、q的值都小于root,说明p q 肯定在root的左子树中;
121+
//如果p q都大于root,说明肯定在root的右子树中
122+
//如果一个在左一个在右 则说明此时的root记为对应的最近公共祖先
123+
if root.Val > p.Val && root.Val > q.Val {
124+
root = root.Left
125+
} else if root.Val < p.Val && root.Val < q.Val {
126+
root = root.Right
127+
} else {
128+
return root
129+
}
130+
}
131+
return nil
132+
}
106133
```
107134

108-
<!-- tabs:end -->
135+
<!-- tabs:end -->
136+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Definition for TreeNode.
3+
* type TreeNode struct {
4+
* Val int
5+
* Left *ListNode
6+
* Right *ListNode
7+
* }
8+
*/
9+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
10+
if root == nil {
11+
return nil
12+
}
13+
14+
for root != nil {
15+
//如果p、q的值都小于root,说明p q 肯定在root的左子树中;
16+
//如果p q都大于root,说明肯定在root的右子树中
17+
//如果一个在左一个在右 则说明此时的root记为对应的最近公共祖先
18+
if root.Val > p.Val && root.Val > q.Val {
19+
root = root.Left
20+
} else if root.Val < p.Val && root.Val < q.Val {
21+
root = root.Right
22+
} else {
23+
return root
24+
}
25+
}
26+
return nil
27+
}

0 commit comments

Comments
(0)

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