尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 305
已运行时间: 1057
目录
  1. BFS
  2. DFS

尼采般地抒情

尼采般地抒情

公告栏

此网站主题为本人手写主题, 主题待开源···

站点信息

文章总数目: 305
已运行时间: 1057

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
  };

评论区

Twikoo giscus