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; } ...