Skip to main content

Posts

Leetcode 95: Unique Binary Search Trees II

  1. Problem Summary You’re given an integer n. You need to generate  all structurally unique Binary Search Trees (BSTs)  that: Have exactly n nodes. Use all values from 1 to n  exactly once  (each value appears in exactly one node). Follow BST property: left subtree < root < right subtree. Input:   n (1 ≤ n ≤ 8) Output:  A list of all different BST root nodes (trees), each representing a unique structure and node arrangement. The order of the trees returned doesn’t matter. 2. Examples Explanation Example 1: Input:  n = 3 Possible unique BST structures using values 1, 2, 3: Root 1: Right: BST formed from [2, 3] → options: 1 -> right = 2 -> right = 3 → [1,null,2,null,3] 1 -> right = 3, left child of 3 is 2 → [1,null,3,2] Root 2: Left: 1, Right: 3 → [2,1,3] Root 3: Left: BST formed from [1, 2] → options: 3 -> left = 1 ...

Leetcode 94: Binary Tree Inorder Traversal

  1. Problem Summary You’re given the root of a binary tree and must return the  inorder traversal  of its node values. Inorder traversal definition: For each node, visit: Left subtree The node itself Right subtree Input :  root (binary tree root, may be null) Output :  List/array of integers representing the inorder traversal. Constraints : 0 <= number of nodes <= 100 -100 <= Node.val <= 100 Follow-up: implement  iteratively , not just recursively. 2. Examples Explanation Example 1: Input:  root = [1,null,2,3] The tree: 1 right → 2 left → 3 Inorder (Left, Node, Right): Left of 1 is null Visit 1 Inorder of right subtree (2): Left of 2 is 3 → visit 3 Visit 2 Result: [1, 3, 2]. Example 2: Input:  root = [1,2,3,4,5,null,8,null,null,6,7,9] Inorder traversal results in: [4, 2, 6, 5, 7, 1, 3, 9, 8] This comes from visiting each subtree in Left → Node → Right order. Ex...