xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 二叉树测试用例生成器 All In One

LeetCode 二叉树测试用例生成器 All In One

二叉树生成器 / Binary Tree Generator

实现原理

递归依次遍历数组从左到右(左=>右),遇到 null 返回 (✅ null 后面不能有子节点了)

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-01-01
 * @modified
 *
 * @description LeetCode 二叉树测试用例生成器
 * @difficulty Easy
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link 
 * @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);
  }
}

// LeetCode tree testcase generator
// 二叉树生成原理:递归依次遍历(左=>右),遇到 null 返回 (✅ null 后面不能有子节点了)
const BinaryTreeGenerator = (arr = [], i = 0): (TreeNode | null) => {
  // (arr.length - 1)下标越界 或 null 返回 null
  if(i >= arr.length || arr[i] === null) {
    return null;
  }
  const node = new TreeNode(arr[i]);
  // 先左后右, 依次遍历
  node.left = BinaryTreeGenerator(arr, 2 * i + 1);
  node.right = BinaryTreeGenerator(arr, 2 * i + 2);
  return node ;
}


js 测试 ✅

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

const BinaryTreeGenerator = (arr = [], i = 0) => {
  if(i > arr.length || arr[i] === null) {
    return null;
  }
  const node = new TreeNode(arr[i]);
  node.left = BinaryTreeGenerator(arr, 2 * i + 1);
  node.right = BinaryTreeGenerator(arr, 2 * i + 2);
  return node ;
}

const bt = BinaryTreeGenerator([3,9,20,null,null,15,7]);

/*
{
  "val": 3,
  "left": {
    "val": 9,
    "left": null,
    "right": null
  },
  "right": {
    "val": 20,
    "left": {
      "val": 15,
      "left": null,
      "right": null
    },
    "right": {
      "val": 7,
      "left": null,
      "right": null
    }
  }
}
*/

image

image

https://leetcode.com/problems/maximum-depth-of-binary-tree/

bug ???

image

const log = console.log;

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

const BinaryTreeGenerator = (arr = [], i = 0) => {
  if(arr.length === 0 || i > arr.length || arr[i] === null) {
    return null;
  }
  const node = new TreeNode(arr[i]);
  // 先左后右, 依次遍历
  node.left = BinaryTreeGenerator(arr, 2 * i + 1);
  node.right = BinaryTreeGenerator(arr, 2 * i + 2);
  return node ;
}

BinaryTreeGenerator([1,2,2,3,4,4,3]);

const tree = BinaryTreeGenerator([1,2,2,3,4,4,3]);

// log(`tree`, tree);
log(`tree =`, JSON.stringify(tree, null, 4));

const json = {
    "val": 1,
    "left": {
        "val": 2,
        "left": {
            "val": 3,
            // bug ❌
            "left": {
                "val": 0,
                "left": null,
                "right": null
            },
            "right": null
        },
        "right": {
            "val": 4,
            "left": null,
            "right": null
        }
    },
    "right": {
        "val": 2,
        "left": {
            "val": 4,
            "left": null,
            "right": null
        },
        "right": {
            "val": 3,
            "left": null,
            "right": null
        }
    }
};


bug fix

// arr[i] === undefined ✅
const BinaryTreeGenerator = (arr: any[] = [], i: number = 0): (TreeNode | null) => {
  if(arr.length === 0 || i > arr.length || arr[i] === null || arr[i] === undefined) {
    return null;
  }
  const node = new TreeNode(arr[i]);
  // 先左后右, 依次遍历
  node.left = BinaryTreeGenerator(arr, 2 * i + 1);
  node.right = BinaryTreeGenerator(arr, 2 * i + 2);
  return node ;
}

或者

// i >= arr.length ✅
const BinaryTreeGenerator = (arr: any[] = [], i: number = 0): (TreeNode | null) => {
  if(arr.length === 0 || i >= arr.length || arr[i] === null) {
    return null;
  }
  const node = new TreeNode(arr[i]);
  // 先左后右, 依次遍历
  node.left = BinaryTreeGenerator(arr, 2 * i + 1);
  node.right = BinaryTreeGenerator(arr, 2 * i + 2);
  return node ;
}

image

https://leetcode.com/problems/symmetric-tree/

数据可视化

二叉树动态生成器动效
二叉树动态生成器组件

LeetCode 二叉树生成器是纯函数

  1. 测试用例输入数据源相同:[3,9,20,null,null,15,7]
  2. 输出的二叉树结构也一样,具有一致性/幂等性

纯函数

  • 如果函数的调用参数相同,则永远返回结果相同; 它不依赖于程序执行期间函数外部任何状态或数据的变化,只依赖于其输入参数

  • 该函数不会产生任何可观察的副作用,例如网络请求,输入和输出设备或数据突变(mutation)。

幂等函数或幂等方法是指可以使用相同参数重复执行,并能获得相同结果的函数。

image

image

https://leetcode.com/problems/maximum-depth-of-binary-tree/

https://leetcode.com/problems/symmetric-tree/

...

D3.js => SVG / Canvas

demos

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-01-29
 * @modified 2023-02-05
 *
 * @description 104. 二叉树的最大深度
 * @description 104. Maximum Depth of Binary Tree
 * @difficulty Easy
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/maximum-depth-of-binary-tree/
 * @link https://leetcode.cn/problems/maximum-depth-of-binary-tree/
 * @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);
  }
}

function maxDepth(root: TreeNode | null): number {
  if(root === null) {
    return 0;
  }
  const arr: number[] = [];
  function dfs (node, init = 0) {
    let deep = init;
    deep += 1;
    if(node.left === null && node.right === null) {
      // leaf node
      arr.push(deep);
      return;
    }
    if(node.left !== null) {
      dfs(node.left, deep);
    }
    if(node.right !== null) {
      dfs(node.right, deep);
    }
  }
  dfs(root);
  return Math.max(...arr);
};

// LeetCode tree test case
// 二叉树生成原理:递归依次遍历(左=>右),遇到 null 返回 (✅ null 后面不能有子节点了)
const BinaryTreeGenerator = (arr = [], i = 0): (TreeNode | null) => {
  if(arr.length === 0 || i > arr.length || arr[i] === null) {
    return null;
  }
  const node = new TreeNode(arr[i]);
  // 先左后右, 依次遍历
  node.left = BinaryTreeGenerator(arr, 2 * i + 1);
  node.right = BinaryTreeGenerator(arr, 2 * i + 2);
  return node ;
}

// 测试用例 test cases
const testCases = [
  {
    input: [3,9,20,null,null,15,7],
    result: 3,
    desc: 'value equal to 3',
    img: 'https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg',
  },
  {
    input: [1,null,2],
    result: 2,
    desc: 'value equal to 2',
  },
  {
    input: [],
    result: 0,
    desc: 'value equal to 0',
  },
];

/*
const testCase: {
    input: (number | null)[];
    result: number;
    desc: string;
    img: string;
} | {
    input: (number | null)[];
    result: number;
    desc: string;
    img?: undefined;
}

*/

for (const [i, testCase] of testCases.entries()) {
  const tree = BinaryTreeGenerator(testCase.input as []);
  const result = maxDepth(tree);
  log(`test case ${i} result: `, result === testCase.result ? `✅ passed` : `❌ failed`, result);
}



/*
$ npx ts-node ./104\ maximum-depth-of-binary-tree.ts

*/

image

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

ChatGPT

LeetCode 二叉树生成器 / Binary Tree Generator

https://chat.openai.com/chat/330a8d3e-e74c-471f-9ed9-cac30f0a2ab9

class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = this.right = null;
  }
}

function createBinaryTree(arr, i = 0) {
  if (i >= arr.length || arr[i] === null) return null;
  let node = new TreeNode(arr[i]);
  node.left = createBinaryTree(arr, 2 * i + 1);
  node.right = createBinaryTree(arr, 2 * i + 2);
  return node;
}

https://www.cnblogs.com/xgqfrms/tag/ChatGPT/

https://www.cnblogs.com/xgqfrms/p/17081303.html#5146399

https://www.cnblogs.com/xgqfrms/p/17080136.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-02-05 17:20  xgqfrms  阅读(600)  评论(5编辑  收藏  举报