File tree 2 files changed +58
-3
lines changed
solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree
2 files changed +58
-3
lines changed Original file line number Diff line number Diff line change @@ -100,9 +100,37 @@ class Solution {
100
100
}
101
101
```
102
102
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
+ }
105
118
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
+ }
106
133
```
107
134
108
- <!-- tabs:end -->
135
+ <!-- tabs:end -->
136
+
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments