5

将leetcode中二叉树的数组结构转为真实的树结构

 2 years ago
source link: https://www.xiabingbao.com/post/js/leetcode-treenode-array.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

将leetcode中二叉树的数组结构转为真实的树结构

蚊子前端博客
发布于 2021-06-07 17:39
将leetcode中二叉树的数组结构转为真实的树结构

我们在 LeetCode 上锻炼算法时,关于二叉树的题目,网站上给的都直接是一个数组,那么本地测试的时候,就很不方便。

官方文档中的解释是这样的:[请问 [1, null, 2, 3] 在二叉树测试用例中代表什么](https://support.leetcode-cn.com/hc/kb/article/1194353/)。

这里写了一个 js 方法,将数组转为二叉树结构:

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

const array2binary = (arr) => {
  if (!arr || !arr.length) {
    return null;
  }
  let index = 0;
  const queue = [];
  const len = arr.length;
  const head = new TreeNode(arr[index]);
  queue.push(head);

  while (index < len) {
    index++;
    const parent = queue.shift();
    if (arr[index] !== null && arr[index] !== undefined) {
      const node = new TreeNode(arr[index]);
      parent.left = node;
      queue.push(node);
    }

    index++;
    if (arr[index] !== null && arr[index] !== undefined) {
      const node = new TreeNode(arr[index]);
      parent.right = node;
      queue.push(node);
    }
  }
  return head;
};
const root = array2binary([3, 9, 20, null, null, 15, 7]);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK