题目判断二叉树是否完全一样
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
- Example 1
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
- Example 2
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
- Example 3
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
- 解法
var isSameTree = function(p, q) {
//BFS
function getBfsPath(root){
let path = []
let nodes = []
nodes.push(root)
while(nodes.length > 0){
let node = nodes.shift()
if(!node){
path.push(null)
}else{
path.push(node.val)
nodes.push(node.left)
nodes.push(node.right)
}
}
return path
}
// 比较二者数组是否完全一样
function arrayEqual(arr1,arr2){
const flag = arr1.length === arr2.length && arr1.every((val,idx) => val === arr2[idx])
return flag
}
return arrayEqual(getBfsPath(p),getBfsPath(q))
};
- 题目思路
利用广度优先搜索(BFS),得出两个节点的数组路径,然后一一对比