leetcode-Easy-29-Tree-Same|leetcode-Easy-29-Tree-Same tree

题目判断二叉树是否完全一样

【leetcode-Easy-29-Tree-Same|leetcode-Easy-29-Tree-Same tree】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:11 / \/ \ 2323[1,2,3],[1,2,3]Output: true

  • Example 2
Input:11 /\ 22[1,2],[1,null,2]Output: false

  • Example 3
Input:11 / \/ \ 2112[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),得出两个节点的数组路径,然后一一对比

    推荐阅读