same tree
Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
What we can do here is do a recursive depth-first search on both trees and compare the node values on each recursive call.
We return false if the node values aren’t equal at any point otherwise return true. The base case return true
when both tree nodes are null
or return false
when the nodes aren’t equal.
var isSameTree = function(p, q) {
if(p === null && q !== null) {
return false;
}else if(p !== null && q === null) {
return false;
}else if(p === null && q === null) {
return true;
}else if(p.val !== q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};