BFS
/**
* 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
if (p === null || q === null) return false
let que_1 = [p]
let que_2 = [q]
while(que_1.length !== 0) {
let que_1_size = que_1.length
let que_2_size = que_2.length
if (que_1_size !== que_2_size) return false
for (let i = 0; i<que_1_size; i++) {
let mp1 = que_1.shift()
let mp2 = que_2.shift()
if (mp1.val !== mp2.val) return false
if (mp1.left && mp2.left) {
que_1.push(mp1.left)
que_2.push(mp2.left)
} else if(!mp1.left && !mp2.left){} else {
return false
}
if (mp1.right && mp2.right) {
que_1.push(mp1.right)
que_2.push(mp2.right)
} else if(!mp1.right && !mp2.right){} else {
return false
}
}
}
return true
};
DFS
肝不动了,直接暴力run ok就行
/**
* 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) {
let result = true
if (p === null && q === null) return result
if (p === null || q === null) return !result
let arr_1 = []
let arr_2 = []
let dfs = (data, arr) => {
if (data) {
arr.push(data.val)
if (data.left) {
dfs(data.left, arr)
} else {
arr.push(99999)
}
if (data.right) {
dfs(data.right, arr)
} else {
arr.push(99999)
}
}
}
dfs(p, arr_1)
dfs(q, arr_2)
if (arr_1.length !== arr_2.length) result = false
arr_1.forEach((data, index) => {
if (data !== arr_2[index]) {
result = false
}
})
return result
};