Same Binary Tree
The Question
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value. You can practice it on leetcode before reading the solution
Solution
Let us break the question up to an objective parts
The first Idea when we have tree is recursion as we never know their depth. We have 2 steps here.
- Check if the roots are same (both null or both have same val)
- If they are not then return false
- if the root is same then we check if the respective left and right are same
Code In Java
Evaluation
Theoretical
Space Complexity: O(h)
Time Complexity: O(n)
Leetcode
Memory: 34.1MB
Runtime: 0 ms