首页 > 编程语言 >广度优先搜索算法 BFS 实战 All In One

广度优先搜索算法 BFS 实战 All In One

时间:2023-02-01 15:35:27浏览次数:41  
标签:right const val 搜索算法 BFS 广度 null root left

广度优先搜索算法 BFS 实战 All In One

Breadth-First Search / BFS

BFS / 广度优先搜索 / 广度优先遍历 / 按层次遍历树

image

demos

LeetCode

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-01-31
 * @modified
 *
 * @description 2196. Create Binary Tree From Descriptions
 * @description 2196. 根据描述创建二叉树
 * @difficulty Medium
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/create-binary-tree-from-descriptions/
 * @link https://leetcode.cn/problems/create-binary-tree-from-descriptions/
 * @solutions
 *
 * @best_solutions
 *
 */

export {};

const log = console.log;

class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = (val === undefined ? 0 : val);
    this.left = (left === undefined ? null : left);
    this.right = (right === undefined ? null : right);
  }
}

// [parent, child, isLeft]
// isLefti == 1,true
// isLefti == 0, false

const findRoot = (nodes) => {
  if(nodes.length === 1) {
    return nodes[0][0];
  } else {
    const parents: number[] = [];
    const childs: number[] = [];
    // const parents = [];
    // const childs = [];
    for(let node of nodes) {
      const [parent, child] = node;
      parents.push(parent);
      childs.push(child);
    }
    for(let node of nodes) {
      const [parent, child] = node;
      if(!childs.includes(parent)) {
        return parent;
      }
    }
  }
}

/*

findRoot([[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]])
// 50
findRoot([[1,2,1],[2,3,0],[3,4,1]]);
// 1
 */


/*

[[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]

[50,20,80,15,17,19]

*/

// DFS 深度优先搜索 / 深度优先遍历
function dfs(root, nodes) {
  const childs = nodes.filter(item => item[0] === root.val);
  for(let node of childs) {
    const [parent, child, isLeft] = node;
    if(isLeft) {
      root.left = new TreeNode(child);
      dfs(root.left, nodes);
    } else {
      root.right = new TreeNode(child);
      dfs(root.right, nodes);
    }
  }
}

function createBinaryTree(descriptions: number[][]): TreeNode | null {
  const rootValue = findRoot(descriptions);
  const root = new TreeNode(rootValue);
  dfs(root, descriptions);
  return root;
};


// 按层次遍历树,BFS 广度优先搜索/遍历
function bfs(root, arr) {
  if(root === null) {
    return;
  }
  // 去重
  if(!arr.includes(root.val)) {
    arr.push(root.val)
  }
  // 先同层遍历
  if(root.left !== null && root.left.val) {
    arr.push(root.left.val)
  }
  if(root.right !== null && root.right.val) {
    arr.push(root.right.val)
  }
  // 后递归深度遍历
  if(root.left !== null) {
    bfs(root.left, arr)
  }
  if(root.right !== null) {
    bfs(root.right, arr)
  }
}

function getBinaryTreeValues(root: TreeNode | null) {
  const arr = [];
  // 按层次遍历树,BFS 广度优先搜索/遍历
  bfs(root, arr);
  return arr;
};


/*


Constraints:

1 <= descriptions.length <= 104
descriptions[i].length == 3
1 <= parenti, childi <= 105
0 <= isLefti <= 1
The binary tree described by descriptions is valid.

*/


// 测试用例 test cases
const testCases = [
  {
    input: [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]],
    result: [50,20,80,15,17,19],
    desc: 'value equal to [50,20,80,15,17,19]',
  },
  {
    input: [[1,2,1],[2,3,0],[3,4,1]],
    result: [1,2,null,null,3,4],
    desc: 'value equal to [1,2,null,null,3,4]',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const result = createBinaryTree(testCase.input);
  const values = getBinaryTreeValues(result);
  const nums = testCase.result.filter(i => i !== null);
  log(`values =`, values);
  log(`nums =`, nums);
  log(`test case ${i} result: `, JSON.stringify(values) === JSON.stringify(nums) ? `✅ passed` : `❌ failed`);
  // log(`test case ${i} result: `, JSON.stringify(values) === JSON.stringify(nums) ? `✅ passed` : `❌ failed`, result);
}

/*

$ npx ts-node ./2196\ create-binary-tree-from-descriptions.ts

*/

(

标签:right,const,val,搜索算法,BFS,广度,null,root,left
From: https://www.cnblogs.com/xgqfrms/p/17082942.html

相关文章

  • 倍增+bfs 清楚姐姐逛街
    题目https://ac.nowcoder.com/acm/contest/46812/H题意地图大小N*M,障碍物为“#”,地图上其他所有点有一个字母(“LRUD”之一,表示走的方向;“.”表示A停止)有两个人A和B,A......
  • Knight Moves POJ-1915 <bfs>
    KnightMovesTimeLimit: 1000MS MemoryLimit: 30000KTotalSubmissions: 37011 Accepted: 17105DescriptionBackgroundMrSomurolov,fabulous......
  • 图文:深度优先遍历(DFS)和广度优先遍历(BFS)
    /***注意:left/right值若没有显示设置为null,值即为undefined*在调用二叉树前、中、后序遍历方法时,由于参数设置了默认值(tree)*所以进入了死循环*/consttree={......
  • bfs走迷宫
    广度优先搜索(也称宽度优先搜索,缩写BFS,以下采用广度来描述)是连通图的一种遍历算法这一算法也是很多重要的图的算法的原型。Dijkstra单源最短路径算法和Prim最小生成树算法都......
  • 【BFS】LeetCode 417. 太平洋大西洋水流问题
    题目链接417.太平洋大西洋水流问题思路问题可以转换成从四个边界出发,能和内部哪些点连通。因为涉及到两个可达性问题,所以用两个boolean类型矩阵分别记录一个点到太......
  • 【BFS】LeetCode 542. 01 矩阵
    题目链接542.01矩阵思路题目让求1到0的距离,其实可以转换成求0到1的距离,将所有的0作为源结点放入队列进行BFS。BFS本质上就是从源点开始的搜索算法,本题只不过是所有的......
  • 【BFS】LeetCode 1091. 二进制矩阵中的最短路径
    题目链接1091.二进制矩阵中的最短路径思路BFS找最短路模板题代码classSolution{publicintshortestPathBinaryMatrix(int[][]grid){if(grid[0][......
  • D. Friendly Spiders(bfs最短路径、质数虚点建图)
    题意:给一个长度为n的数组a,数组中两两不互质的数可以建一条边,即$gcd(a[i],a[j])≠1$,i,j之间存在伊奥无向边问s到t的最短路径是多长,并输出题解根据唯一分解......
  • 【BFS】LeetCode 133. 克隆图
    题目链接133.克隆图思路代码classSolution{publicNodecloneGraph(Nodenode){if(node==null){returnnode;}H......
  • 【BFS】LeetCode 297. 二叉树的序列化与反序列化
    题目链接297.二叉树的序列化与反序列化思路代码classCodec{//Encodesatreetoasinglestring.publicStringserialize(TreeNoderoot){i......