LeetCode:100.相同的树
两个树:根节点的值相同,左子树相同,右子树相同。符合“分、解、合”特性。考虑选择分而治之。
分:获取两个树的左子树和右子树。解:递归地判断两个树的左子树是否相同,右子树是否相同。合:将上述结果合并,如果根节点的值也相同,树就相同。
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if(p===null&&q!==null){
return false
}
if(p!==null&&q===null){
return false
}
if(p===null&&q===null){
return true
}else{
return p.val===q.val&&isSameTree(p.left,q.left) && isSameTree(p.right,q.right)
}
return isSameTree(p,q)
};
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if(!p&&!q)return true;
if(p&&q&&q.val===p.val&&isSameTree(p.left,q.left)&&isSameTree(p.right,q.right)){
return true;
}
return false;
};
'
标签:right,return,val,相同,&&,100,null,LeetCode,left From: https://www.cnblogs.com/KooTeam/p/18675180