701. Insert into a Binary Search Tree ¶ Time: $O(\log n) \to O(n)$ Space: $O(\log n) \to O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public: TreeNode* insertIntoBST(TreeNode* root, int val) { if (root == nullptr) return new TreeNode(val); if (root->val > val) root->left = insertIntoBST(root->left, val); else root->right = insertIntoBST(root->right, val); return root; } }; 1 2 3 4 5 6 7 8 9 10 11class Solution { public TreeNode insertIntoBST(TreeNode root, int val) { if (root == null) return new TreeNode(val); if (root.val > val) root.left = insertIntoBST(root.left, val); else root.right = insertIntoBST(root.right, val); return root; } } 1 2 3 4 5 6 7 8 9class Solution: def insertIntoBST(self, root: TreeNode | None, val: int) -> TreeNode | None: if not root: return TreeNode(val) if root.val > val: root.left = self.insertIntoBST(root.left, val) else: root.right = self.insertIntoBST(root.right, val) return root