98. Validate Binary Search Tree#27
Conversation
| if (!root) { | ||
| return true; | ||
| } | ||
| if (root->val >= max || root->val <= min) { |
There was a problem hiding this comment.
if (!(min < root->val && root->val < max)) {と、数直線上に一直線になるように書くと、読み手にとって理解しやすくなると思います。
There was a problem hiding this comment.
そうですね、ご指摘ありがとうございます。
| */ | ||
| class Solution { | ||
| public: | ||
| bool traverse(TreeNode* root, long long min, long long max) { |
There was a problem hiding this comment.
関数名は UpperCamel で書くことが多いかもしれません。 LeetCode で指定されているものについては、指定された通りに書かざるを得ないのですが…。
参考までにスタイルガイドへのリンクを共有いたします。
https://google.github.io/styleguide/cppguide.html#Function_Names
Ordinarily, functions follow PascalCase: start with a capital letter and have a capital letter for each new word.
なお、このスタイルガイドは“唯一の正解”というわけではなく、数あるガイドラインの一つに過ぎません。チームによって重視される書き方や慣習も異なります。そのため、ご自身の中に基準を持ちつつも、最終的にはチームの一般的な書き方に合わせることをお勧めします。
There was a problem hiding this comment.
そうですね、ご指摘ありがとうございます。LeetCodeの書き方に釣られてLower camel caseで書いてしまっていました。
| if (root->val >= max || root->val <= min) { | ||
| return false; | ||
| } | ||
| return traverse(root->left, min, root->val) |
There was a problem hiding this comment.
改行する際は論理演算子を行末に書く場合もあります。
https://google.github.io/styleguide/cppguide.html#Boolean_Expressions
Note that when the code wraps in this example, both of the && logical AND operators are at the end of the line. This is more common in Google code, though wrapping all operators at the beginning of the line is also allowed.
| } | ||
|
|
||
| bool isValidBST(TreeNode* root) { | ||
| return traverse(root, LLONG_MIN, LLONG_MAX); |
There was a problem hiding this comment.
LLONG_MIN/LLONG_MAX は C 言語風に感じます。 C++11 以降では std::numerical_limits<int64_t>::min()/max() を使用することをお勧めいたします。
There was a problem hiding this comment.
ご指摘ありがとうございます。そちらを使うようにします。
| */ | ||
| class Solution { | ||
| public: | ||
| bool traverse(TreeNode* root, long long min, long long max) { |
There was a problem hiding this comment.
個人的には long long の代わりに int64_t を使うことが多いです。 long long は 64 ビット以上であることが保証されているのに対し、 int64_t は 64 ビットであることが保証されているようです。
https://cpprefjp.github.io/lang/cpp11/long_long_type.html
There was a problem hiding this comment.
そうなんですね、ご指摘ありがとうございます。たしかに64ビットであることが保証されている方が安心して使えそうな気がします。
| */ | ||
| class Solution { | ||
| public: | ||
| bool traverse(TreeNode* root, long long min, long long max) { |
There was a problem hiding this comment.
root は、木の根ノードを表す用語です。探索中のノードを表す変数名に付けるには違和感を感じます。 node はいかがでしょうか?
There was a problem hiding this comment.
そうですね、nodeの方がよさそうです。
この問題:https://leetcode.com/problems/validate-binary-search-tree/description/
次に解く問題:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/