Skip to content

Commit e48ce1d

Browse files
authored
Merge pull request #29 from rihib/lowest_common_ancester_of_a_binary_search_tree
Lowest Common Ancestor of a Binary Search Tree
2 parents 8b698d6 + 6a53520 commit e48ce1d

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
該当ノードが見つからなかったからといってプログラムの実行の継続が困難になるわけではないと思うので、panicやlog.Panicを使うのはやり過ぎだと思います。
18+
場合によっては絶対に見つからないことが起こる入力はしないはずだと言える状況であればlog.Fatalを使ってログに書き込んだ後にos.Exit(1)を呼び出してプログラムを終了させるのが良い可能性もありますが、それも通常の場合やりすぎな気がします。
19+
他にはlog.Printなどを使ってログに見つからなかったことを記録しても良いかもしれませんが、見つからないことが起こる入力があり得るのであれば単にerrorを返り値として返して呼び出し側で処理するのが良いと思っています。
20+
他には単に見つからなかった場合はnilを返すなども手としてはあると思いますが、そうする場合は呼び出し側にもわかるようにコメント等で書いておいて欲しいなと思います。
21+
*/
22+
func lowestCommonAncestorIterativeStep1(root, p, q *TreeNode) *TreeNode {
23+
node := root
24+
for node != nil {
25+
if p.Val <= node.Val && node.Val <= q.Val || q.Val <= node.Val && node.Val <= p.Val {
26+
return node
27+
}
28+
if p.Val < node.Val && q.Val < node.Val {
29+
node = node.Left
30+
}
31+
if node.Val < p.Val && node.Val < q.Val {
32+
node = node.Right
33+
}
34+
}
35+
return nil
36+
}
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)