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:     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),得出两个节点的数组路径,然后一一对比
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,141评论 0 10
  • 在福州只住了一夜,到达已是晩饭时分。石修银老兄陪我夜逛三坊七巷,从宾馆步行前往,首先一万步达标!其次用《水...
    张玉新关东汉子阅读 4,560评论 3 4
  • 有人过来告诉我,你拍的一张人物照真美,上图。惊喜之余,才发现,原来这个世界最美的东西源于分享! 文中的图片几乎都是...
    野性丽丽阅读 4,390评论 6 10
  • 千古形胜,陈仓道,山川满目苍痍。风云突变难销尽,多少英雄得意。蜀道崎岖,剑阁峥嵘,北伐终无济。阳平西出,东进长...
    伏牛_阅读 2,924评论 3 2
  • 今天是2018年3月8号,从2017年4月15日辞职距今已经有327天,快一年了,辞职在家时准备考进体制内,这也是...
    Im小段阅读 663评论 0 0