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.
判斷兩棵二叉樹(shù)樹(shù)是不是完全相同的
遞歸梗摇,先看兩個(gè)同一個(gè)位置的節(jié)點(diǎn)是不是相等(包括是否為空献雅,值):
如果是且不為空媒鼓,就把這兩個(gè)節(jié)點(diǎn)左右節(jié)點(diǎn)分別傳進(jìn)去繼續(xù)往下比雀摘,看這個(gè)節(jié)點(diǎn)的左子樹(shù)和右子樹(shù)是不是相等诞吱,返回結(jié)果的與;
如果都為空返回true;
其他情況返回false粱侣;
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if (p!==null&&q!==null) {
if (p.val===q.val){
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
} else {
return false;
}
} else if (p===null&&q===null){
return true;
} else {
return false;
}
};