Posts

Showing posts with the label tree

Same Tree

Same Tree You are given the roots of two binary trees, p and q . Your task is to determine whether the two trees are the same. Two binary trees are considered the same if they are structurally identical and the nodes have the same values . Example Input: p = [ 1 , 2 ] q = [ 1 , null, 2 ] Output: false Constraints The number of nodes in both trees is in the range [0, 100] . -10^4 <= Node.val <= 10^4 Best Data Structure for the Job Trees are already built using the classic TreeNode class. We just need: A recursive function to traverse both trees in parallel. Different Approaches Approach 1: Recursive (Depth-First Search) We traverse both trees simultaneously using recursion. At every node, we compare the values and recursively compare the left and right subtrees. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } ...

Tree Twins: Are You a Mirror?

Mirror Check – A Symmetric Tree Validation Problem Problem Statement Given the root of a binary tree, determine whether the tree is symmetric around its center. A tree is symmetric if the left subtree is a mirror reflection of the right subtree. Example Input: root = [1,2,2,3,4,4,3] Output: true Explanation: The left and right subtrees of the root are mirror images at every level. Hence, the tree is symmetric. Best Data Structure for the Job This problem is fundamentally about comparing two subtrees. A recursive traversal is natural for tree structures, allowing easy mirroring checks between corresponding left and right children. For an iterative solution, a queue can be used to compare nodes level by level in a mirrored fashion. Different Approaches Approach 1: Recursive Mirror Comparison Use a helper function that recursively checks if the left and right subtrees are mirrors of each other. class TreeNode { int val; TreeNode left, right; TreeNode( int ...