Leetcode - Insert into a Binary Search Tree (Python)

preview_player
Показать описание
October 2020 Leetcode Challenge
Leetcode - Insert into a Binary Search Tree #701
Рекомендации по теме
Комментарии
Автор

This problem scared me too for a bit until I noticed you could return 'any' valid BST. Thanks Tim!

janmichaelaustria
Автор

Thanks! What is the time complexity of the insertion operation?

d
Автор

Why can we not put the `if not root: return TreeNode(val)` within the `insert` function? I tried it and it fails on the null cases.

JL
Автор

is the insert() helper function necessary? how about using that same logic but within the parent function and replace those insert() calls with self.insertIntoBST()? you could save 4 lines :^)

for example:

def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root: return TreeNode(val)

if val < root.val:
if not root.left:
root.left = TreeNode(val)
else: self.insertIntoBST(root.left, val)
else:
if not root.right:
root.right = TreeNode(val)
else: self.insertIntoBST(root.right, val)

return root

xvzf