github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。
题目地址:
如下:
Given two integer arrays
preorderandinorderwherepreorderis the preorder traversal of a binary tree andinorderis the inorder traversal of the same tree, construct and return the binary tree.
想要解这道题,首先得了解一下二叉树的几种遍历方式:二叉树先序、中序、后序及层次四种遍历。
知道了前序遍历和中序遍历之后,这道题目就比较好拆解了,以题目中的案例来说:
preorder:
[3,9,20,15,7]
inorder:
[9,3,15,20,7]
已知 preorder 数组中的第一个值为当前结点(root),inorder 使用 inorder[indexOf(preorder[0])] 可以找到当前结点(root),该值左侧为 root 的左子树,右侧为 root 的右子树,根据这个方法就可以拆分出当前二叉树。
依旧以提供的案例来说:
root 为 3
左子树调用 buildTree([9], [9,3])
这里 preorder 的值剔除了当前的 root,所以取值范围为 (0, min]
右子树调用 buildTree([20,15,7], [15,20,7])
取值范围为 (mid, ..., arr.length)
buildTree([9], [9,3]) 的结果返回 TreeNode(3)
buildTree([20,15,7], [15,20,7]) 返回 TreeNode(20)
其左右子树依旧会继续递归调用 buildTree() 去创建新的子节点
// [3, 9, 20,15,7]
// root left
// [9, 3, 15,20,7]
// left root
var buildTree = function (preorder, inorder) {
if (!preorder.length || !inorder.length) return null;
const root = new TreeNode(preorder[0]);
const mid = inorder.indexOf(preorder[0]);
root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid + 1));
root.right = buildTree(preorder.slice(mid + 1), inorder.slice(mid + 1));
return root;
};