Home › Company-wise questions › Google › Insert into a Binary Search Tree ← Google bank
Google · Question 62 · Trees
Insert into a Binary Search Tree Trees Python code ⏱ O(h) 💾 O(h)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Insert a value into a BST and return the root.
Approach Recursively insert in correct subtree.
Time O(h)Space O(h)
How it works 1 If the tree is empty, create the node as root. 2 Go left for smaller values, right otherwise. 3 Attach the new node and return the (unchanged) root. Sample input / output Input:
5
4 2 7 1 3
5
Output:
[4, 2, 7, 1, 3, 5] Constraints 0 <= nodes <= 10^4; -10^8 <= Node.val, val <= 10^8; all values unique.
Solution — read it, then walk it Flowchart Pseudocode
Time O(h)Space O(h)Loops 2Branches 8Returns 6source · Python
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no yes no yes no yes no yes no ↻ repeat yes no yes ↻ repeat ↻ repeat START root, val if not root RETURN TreeNode(val) if val < root.val root.left = insertIntoBST(root.left, val) ELSE root.right = insertIntoBST(root.right, val) RETURN root CLASS TreeNode DEFINE __init__(self, val=0, left=None, right=None) self.val = val self.left = left self.right = right DEFINE build_tree(values) if not values RETURN None root = TreeNode(values[0]) queue = [root] i = 1 while queue and i < len(values) node = queue.pop(0) if i < len(values) and values[i] is not None node.left = TreeNode(values[i]) queue.append(node.left) i += 1 if i < len(values) and values[i] is not None node.right = TreeNode(values[i]) queue.append(node.right) i += 1 RETURN root DEFINE level_order(root) if not root RETURN [] out, queue = [], [root] while queue node = queue.pop(0) if node out.append(node.val) queue += [node.left, node.right] RETURN out DEFINE main() import sys data = sys.stdin.read().split() it = iter(data) n = int(next(it)) start / end statement condition loop returns definition← Q61 · Kth Smallest Element in a BST Q63 · Number of Islands (DFS) → Solution code Core logic highlighted in green
Language Pythonsource Java C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →