将leetcode中二叉树的数组结构转为真实的树结构
我们在 LeetCode 上锻炼算法时,关于二叉树的题目,网站上给的都直接是一个数组,那么本地测试的时候,就很不方便。
官方文档中的解释是这样的:请问 [1, null, 2, 3] 在二叉树测试用例中代表什么。
这里写了一个 js 方法,将数组转为二叉树结构:
COPYJAVASCRIPT
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; };
使用:
COPYJAVASCRIPT
const root = array2binary([3, 9, 20, null, null, 15, 7]);
最终转换成的树形结构: