leetcode --- js版本程序员

leetcode-Easy-29-Tree-Same tree

2019-04-10  本文已影响4人  石头说钱

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

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.

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

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))
};
上一篇 下一篇

猜你喜欢

热点阅读