mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
Optimize arrToTree function
in java, cpp, py, go, js, ts.
This commit is contained in:
@ -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);
|
||||
|
||||
@ -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);
|
||||
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user