编程语言/二叉树:修订间差异
来自康健生活
| 第125行: | 第125行: | ||
} | } | ||
</graphviz> | </graphviz> | ||
<syntaxhighlight lang="javascript"> | |||
/** | |||
* Definition for a binary tree node. | |||
* function TreeNode(val) { | |||
* this.val = val; | |||
* this.left = this.right = null; | |||
* } | |||
*/ | |||
/** | |||
* @param {number[]} preorder | |||
* @param {number[]} inorder | |||
* @return {TreeNode} | |||
*/ | |||
var buildTree = function(preorder, inorder) { | |||
if (!preorder.length || !inorder.length) { | |||
return null; | |||
} | |||
const rootValue = preorder[0]; | |||
const node = new TreeNode(rootValue); | |||
let i = 0; | |||
for (; i < inorder.length; ++i) { | |||
if (inorder[i] === rootValue) { | |||
break; | |||
} | |||
} | |||
node.left = buildTree(preorder.slice(1, i + 1), inorder.slice(0, i)); | |||
node.right = buildTree(preorder.slice(i + 1), inorder.slice(i + 1)); | |||
return node; | |||
};</syntaxhighlight> | |||
{{Unknown|心谭}} | |||