Skip to main content

Posts

Leetcode 100: Same Tree

  1. Problem Summary You are given the roots of two binary trees p and q. You must determine whether the  two trees are the same . Two binary trees are considered the same if: They are  structurally identical  (same shape), and Every corresponding node has the  same value . Input:  roots p and q (each may be null) Output:  Boolean: true if the trees are identical, false otherwise. Constraints: Each tree has 0 to 100 nodes. Node values are in [-10 4 , 10 4 ]. 2. Examples Explanation Example 1: Input: p = [1,2,3], q = [1,2,3] Both trees: Root 1 Left 2 Right 3 Same structure and node values → true. Example 2: Input: p = [1,2], q = [1,null,2] Trees: p: Root 1 Left 2 Right null q: Root 1 Left null Right 2 Different structure (one left child vs one right child) → false. Example 3: Input: p = [1,2,1], q = [...

Leetcode 99: Recover Binary Search Tree

  1. Problem Summary You’re given the root of a  Binary Search Tree (BST)  in which  exactly two nodes’ values have been swapped  by mistake. The tree structure (shape, parent-child links) is unchanged, but the BST ordering property is violated. Your task:  restore the BST  by swapping the values of the two incorrect nodes back,  without changing the tree structure  (i.e., only swap node values). Input: root of a BST with exactly two nodes’ values swapped. Output: The tree corrected in-place (no return value, typically void). Constraints: Number of nodes: [2, 1000] Values: [-2 31 , 2 31 - 1] Follow-up: Solve with  O(1)  extra space (besides recursion stack). 2. Examples Explanation Example 1: Input:  root = [1,3,null,null,2] Tree: 1 left → 3 right → 2 In a correct BST, the left child of 1 must be < 1, but here it’s 3 > 1. If we swap the values of 1 and...