Skip to content

Commit b21c02d

Browse files
committed
pullrequests/lowest_common_ancester_of_a_binary_search_tree
1 parent 41a8260 commit b21c02d

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
//lint:file-ignore U1000 Ignore all unused code
2+
package lowestcommonancesterofabinarysearchtree
3+
4+
type TreeNode struct {
5+
Val int
6+
Left *TreeNode
7+
Right *TreeNode
8+
}
9+
10+
/*
11+
時間:6分30秒
12+
13+
ルートから見ていく時、共通の祖先になっていないときは必ず、pとqは左か右のどちらかの同じ部分木にいるはず。pとqの間の値になったら共通の祖先になったとわかる。
14+
15+
本来は見つからなかった場合は返り値としてerrorを返したかったのですが、LeetCodeの制約上変えられないのでnilを返すようにしています。
16+
*/
17+
func lowestCommonAncestorIterativeStep1(root, p, q *TreeNode) *TreeNode {
18+
node := root
19+
for node != nil {
20+
if p.Val <= node.Val && node.Val <= q.Val || q.Val <= node.Val && node.Val <= p.Val {
21+
return node
22+
}
23+
if p.Val < node.Val && q.Val < node.Val {
24+
node = node.Left
25+
}
26+
if node.Val < p.Val && node.Val < q.Val {
27+
node = node.Right
28+
}
29+
}
30+
return nil
31+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//lint:file-ignore U1000 Ignore all unused code
2+
package lowestcommonancesterofabinarysearchtree
3+
4+
/*
5+
より見やすくなるようにリファクタしました。また、再帰を使った実装もしてみました。
6+
エラー処理についてはStep1と同様です。
7+
*/
8+
func lowestCommonAncestorIterative(root, p, q *TreeNode) *TreeNode {
9+
node := root
10+
for node != nil {
11+
if p.Val < node.Val && q.Val < node.Val {
12+
node = node.Left
13+
continue
14+
}
15+
if node.Val < p.Val && node.Val < q.Val {
16+
node = node.Right
17+
continue
18+
}
19+
return node
20+
}
21+
return nil
22+
}
23+
24+
func lowestCommonAncestorRecursive(root, p, q *TreeNode) *TreeNode {
25+
if p.Val < root.Val && q.Val < root.Val {
26+
return lowestCommonAncestorRecursive(root.Left, p, q)
27+
}
28+
if root.Val < p.Val && root.Val < q.Val {
29+
return lowestCommonAncestorRecursive(root.Right, p, q)
30+
}
31+
return root
32+
}

0 commit comments

Comments
 (0)