(47)~[105] 从前序与中序遍历序列构造二叉树

106 阅读1分钟

这题肯定是要先知道,二叉输的前中后序遍历,都是怎么来的,然后才能分割,网上不同解体思路的方法其实就是以最根本的递归来优化,这是看了一个题解知道对了

var buildTree = function (preorder, inorder) {
	if (inorder.length === 0) {
		return null;
	}
	// 先找到跟节点 前序遍历的第一个
	const root = new TreeNode(preorder[0]);
	// 找左右字节点 左右字节点的分界 就是中序遍历中 跟节点root所在位置
	const midIndex = inorder.indexOf(preorder[0]);

	// 前序遍历的 前面几个(1, midIndex+1) 就是左子树的 前序遍历 中旬遍历的后面几个()就是右子树的中序遍历
	root.left = buildTree(preorder.slice(1, midIndex + 1), inorder.slice(0, midIndex));
	// 道理同上
	root.right = buildTree(preorder.slice(midIndex + 1), inorder.slice(midIndex + 1));

	return root;

};

优化后

var buildTree = function (preorder, inorder) {
	const build = (p_start, p_end, i_start, i_end) => {
		if (p_start > p_end) {
			return null;
		}
		let rootVal = preorder[p_start];
		let root = new TreeNode(rootVal);
		let midInx = inorder.indexOf(rootVal);
		let leftnum = midInx - i_start;

		root.left = build(p_start + 1, p_start + leftnum, i_start, midInx - 1);
		root.right = build(p_start + leftnum + 1, p_end, midInx + 1, i_end);
		return root;
	}

	return build(0, preorder.length - 1, 0, inorder.length - 1);

};