Skip to content

Lowest Common Ancestor of a Binary Search Tree #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 23, 2024

Conversation

rihib
Copy link
Owner

@rihib rihib commented Sep 3, 2024

Lowest Common Ancestor of a Binary Search Treeを解きました。レビューをお願い致します。

問題:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
言語:Go

すでに解いている方々:
colorbox/leetcode#12
NobukiFukui/Grind75-ProgrammingTraining#22
thonda28/leetcode#12

今回のエラー処理について:
#29

無限ループの危険性

今回の場合はValがint型なので問題ないが、float型だとすると値としてNaNが入る可能性があり、その場合はNaNはどの値と比較しても(Nan != n以外は)常にfalseになるので、この書き方だと無限ループになってしまう。

必ずどこかしらでtrueが返ることを期待する書き方をしてしまうと思わぬところで無限ループになる可能性があるのでそもそもこういう書き方自体すべきではない。

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	node := root
	for node != nil {
		if p.Val <= node.Val && node.Val <= q.Val || q.Val <= node.Val && node.Val <= p.Val {
			return node
		}
		if p.Val < node.Val && q.Val < node.Val {
			node = node.Left
		}
		if node.Val < p.Val && node.Val < q.Val {
			node = node.Right
		}
	}
	return nil
}

Copy link

@thonda28 thonda28 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

よいと思いました。

この問題に対してというわけではないですが、Golang だとインデントがスペース4つ分のことが多いのかなと思いました。スペース8つ分にしているのは何か意図があったりしますか?

@rihib
Copy link
Owner Author

rihib commented Sep 3, 2024

@thonda28

この問題に対してというわけではないですが、Golang だとインデントがスペース4つ分のことが多いのかなと思いました。スペース8つ分にしているのは何か意図があったりしますか?

単にGitHub上の表示の問題な気がします。僕の場合はタブを使ってインデントしています。

@thonda28
Copy link

thonda28 commented Sep 3, 2024

@thonda28

この問題に対してというわけではないですが、Golang だとインデントがスペース4つ分のことが多いのかなと思いました。スペース8つ分にしているのは何か意図があったりしますか?

単にGitHub上の表示の問題な気がします。僕の場合はタブを使ってインデントしています。

返信ありがとうございます。ChatGPT に聞いてみたところ、たしかに GitHub のデフォルト設定ではタブがスペース8つ分に変換されて表示されるとのことでした。エディタの設定などでタブを自動でスペース4つ分に置き換えることができるみたいなので、僕が Golang を書いていたときには知らず知らずに置き換わっていてこの現象に出くわさなかったのかもです。

@rihib rihib added the NaN label Sep 23, 2024
@rihib rihib merged commit 40c1c2f into main Sep 23, 2024
@rihib rihib deleted the lowest_common_ancester_of_a_binary_search_tree branch September 23, 2024 13:55
rihib added a commit that referenced this pull request Mar 31, 2025
…search_tree

Lowest Common Ancestor of a Binary Search Tree
rihib added a commit that referenced this pull request Mar 31, 2025
…search_tree

Lowest Common Ancestor of a Binary Search Tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants