目录
1,题目
给你两棵二叉树的根节点 p
和 q
,编写一个函数来检验这两棵树是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
2,代码
2.1深度优先遍历
如果两个二叉树都为空,则二叉树相同;
如果两个二叉树只有一个为空,则两个二叉树一定不相同;
如果两个二叉树都不为空,则先判断根节点的值是否相同;若相同,则分别判断两个二叉树的左子树和右子树是否相同;
/**
* 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 true;
}else if (p===null || q===null){
return false;
}else if(p.val != q.val ){
return false;
}else {
// 该节点 的子树结构一样 且值一样,则继续递归
return isSameTree(p.left,q.left) && isSameTree(p.right,q.right)
}
};
2.2广度优先遍历
锻炼思维
/**
* 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 true;
} else if (p === null || q === null) {
return false;
}
let queue1 = [p];
let queue2 = [q];
while (queue1.length > 0 && queue2.length > 0) {
let node1 = queue1.shift();
let node2 = queue2.shift();
if (node1.val !== node2.val) {
return false;
}
let left1 = node1.left, right1 = node1.right, left2 = node2.left, right2 = node2.right;
if ((left1 === null) !== (left2 === null)) {
return false;
}
if ((right1 === null) !== (right2 === null)) {
return false;
}
if (left1 !== null) {
queue1.push(left1);
}
if (right1 !== null) {
queue1.push(right1);
}
if (left2 !== null) {
queue2.push(left2);
}
if (right2 !== null) {
queue2.push(right2);
}
}
return queue1.length === 0 && queue2.length === 0;
};
3,学习与总结
广度优先思维需要继续加强