Same Tree - LeetCode Daily Challenge
Problem Statement
Given the roots of two binary trees p
and q
, 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.
Example 1
Input: p = [1,2,3], q = [1,2,3]
Output: true
Example 2
Input: p = [10,5,15], q = [10,5,null,null,15]
Output: false
Try here before watching the video.
Video Solution
Java Code
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) {
return true;
}
if(p == null || q == null || p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
C++ Code
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) {
return true;
}
if(p == NULL || q == NULL || p->val != q->val) {
return false;
}
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
Python Code
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if(p == None and q == None):
return True
if(p == None or q == None or p.val != q.val):
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Javascript Code
var isSameTree = function(p, q) {
if(p == null && q == null) {
return true;
}
if(p == null || q == null || p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
Go Code
func isSameTree(p *TreeNode, q *TreeNode) bool {
if(p == nil && q == nil) {
return true
}
if(p == nil || q == nil || p.Val != q.Val) {
return false
}
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}
Complexity Analysis
Time Complexity: O(N), we are processing all the nodes.
Space Complexity: O(N), in the worst-case scenario, the tree can be skewed. Therefore, N recursive function calls will be stored in the stacks. Hence O(N).