Skip to content

Conversation

@TORUS0818
Copy link
Owner

本家:https://leetcode.com/problems/split-bst/description/

本家が有料だったので、以下を解きました。
https://www.lintcode.com/problem/847/

Description
Given a binary search tree (BST) with a root node root and a target value v, the tree is partitioned into two subtrees, one of which has nodes that are both less than or equal to the target value and the other has nodes that are both greater than the target value, where the nodes of the given binary search tree root do not necessarily have nodes with values equal to v.

In addition, most of the structure of the original tree root should be preserved. Simply put, for any child node C that has a parent node P in the original tree, if they are both in the same subtree after the split, then the node C should still be a child node of P.

For the two split subtrees, the one with the highest number of nodes is returned, or if the two subtrees have the same number of nodes, the one with the largest root node value is returned.

if small_tree_nodes_count > large_tree_nodes_count:
return small_root

if small_root.val < large_root.val:
Copy link

Choose a reason for hiding this comment

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

必ず large_root.val のほうが大きくなると思います。

if small_tree_nodes_count > large_tree_nodes_count:
    return small_root
else:
    # small_tree_nodes_count == large_tree_nodes_countの場合はlarge_rootを返す。
    return large_root

とシンプルに書けると思います。ややパズルに感じられるため、コメントで補足したほうがよいと思います。

Copy link
Owner Author

Choose a reason for hiding this comment

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

本当ですね、起きていることへの解像度が低かったです。ありがとうございます。

return None, None

if root.val == v:
small_root = root
Copy link

Choose a reason for hiding this comment

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

small_root = root
small_root.right = None
large_root = root.right

の順で書いたほうが、同じ操作対象が連続で登場するので、短期記憶が汚染されにくくなり、認知負荷が少なくなると思います。

Copy link
Owner Author

Choose a reason for hiding this comment

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

STEP3では、まさにこの点が気になって順序を修正しました(L335-L352)

@Mike0121
Copy link

みました。コード読みやすく感じました。(特にStep3)。
この問題、個人的にまだ難しいと感じるので、再度TROUSさんのコードを参考に解き直してみます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants