Optimize arrToTree function

in java, cpp, py, go, js, ts.
This commit is contained in:
Yudong Jin
2023-01-08 19:03:22 +08:00
parent c411969bd1
commit dcc3b2e35b
29 changed files with 222 additions and 114 deletions

View File

@ -28,10 +28,10 @@ function hierOrder(root) {
/* Driver Code */
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
var root = arrToTree([1, 2, 3, 4, 5, 6, 7, null, null, null, null, null, null, null, null]);
var root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
console.log("\n初始化二叉树\n");
printTree(root);
/* 层序遍历 */
let list = hierOrder(root);
console.log("\n层序遍历的结点打印序列 = " + list);
console.log("\n层序遍历的结点打印序列 = " + list);

View File

@ -40,7 +40,7 @@ function postOrder(root) {
/* Driver Code */
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
var root = arrToTree([1, 2, 3, 4, 5, 6, 7, null, null, null, null, null, null, null, null]);
var root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
console.log("\n初始化二叉树\n");
printTree(root);
@ -58,4 +58,3 @@ console.log("\n中序遍历的结点打印序列 = " + list);
list.length = 0;
postOrder(root);
console.log("\n后序遍历的结点打印序列 = " + list);

View File

@ -14,7 +14,7 @@ function TreeNode(val, left, right) {
}
/**
* Generate a binary tree with an array
* Generate a binary tree given an array
* @param arr
* @return
*/
@ -24,20 +24,21 @@ function arrToTree(arr) {
let root = new TreeNode(arr[0]);
let queue = [root]
let i = 1;
while(queue.length) {
let i = 0;
while (queue.length) {
let node = queue.shift();
if(arr[i] !== null) {
if (++i >= arr.length) break;
if (arr[i] !== null) {
node.left = new TreeNode(arr[i]);
queue.push(node.left);
}
i++;
if(arr[i] !== null) {
if (++i >= arr.length) break;
if (arr[i] !== null) {
node.right = new TreeNode(arr[i]);
queue.push(node.right);
}
i++;
}
return root;
}