Skip to content

Create 776. Split BST.md#47

Open
tokuhirat wants to merge 1 commit intomainfrom
776.-Split-BST
Open

Create 776. Split BST.md#47
tokuhirat wants to merge 1 commit intomainfrom
776.-Split-BST

Conversation

@tokuhirat
Copy link
Owner

This Problem
776. Split BST

Given the root of a binary search tree (BST) and an integer target, split the tree into two subtrees where the first subtree has nodes that are all smaller or equal to the target value, while the second subtree has all nodes that are greater than the target value. It is not necessarily the case that the tree contains a node with the value target.

Additionally, most of the structure of the original tree should remain. Formally, for any child c with parent p in the original tree, if they are both in the same subtree after the split, then node c should still have the parent p.

Return an array of the two roots of the two subtrees in order.

Example 1:
Input: root = [4,2,6,1,3,5,7], target = 2
Output: [[2,1],[4,3,6,null,null,5,7]]

Example 2:
Input: root = [1], target = 1
Output: [[1],[]]

Constraints:

The number of nodes in the tree is in the range [1, 50].
0 <= Node.val, target <= 1000

Next Ploblem
3. Longest Substring Without Repeating Characters
言語: Python

- https://github.com/goto-untrapped/Arai60/pull/54#discussion_r1780641914
- 具体例の考え方について。私も複雑な例から考えてしまっていた。
- コードが書けて正当性について他者に説明できる理解の精度がないといけませんね。
- while で書くパターン。

Choose a reason for hiding this comment

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

以前小田さんから「再帰とループの中間を念頭において、対応関係から相互に変換できるようにしておくといいでしょう。」とコメントをいただいたことがございます。リンク先にコードもございます🙇
Ryotaro25/leetcode_first60#50 (comment)

Copy link
Owner Author

Choose a reason for hiding this comment

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

再帰とループの対応は考えてましたが中間というものは考えたことがありませんでした。
Python では書きにくそうですね。コメントありがとうございます。

return [None, None]

if root.val <= target:
smaller, greater = self.splitBST(root.right, target)

Choose a reason for hiding this comment

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

smarller_root greater_rootとする方が分かりやすいと感じました。

node_in_greater_bst = node_in_greater_bst.left
node = node.left
node_in_greater_bst.left = None
return [smaller_bst_root.right, greater_bst_root.left]

Choose a reason for hiding this comment

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

これ再帰を使わなくて済んでとても良いと思いました。

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.

3 participants