題目:
題解:
思路:使用遞歸,看到這個題的時候,我第一反應就是給出先序和中序遍歷序列,構造二叉樹,嗯啊,就是使用這個思路走的。雖然複雜度很高,但是還是很快跑出來了。
代碼:
var constructMaximumBinaryTree = function (nums) {
if (nums.length === 0) {
return null
}
let root = Math.max(...nums);
let index = nums.indexOf(root)
let rootTree = new TreeNode(root)
let left = nums.slice(0, index)
let right = nums.slice(index + 1)
rootTree.left = constructMaximumBinaryTree(left)
rootTree.right = constructMaximumBinaryTree(right)
return rootTree
};
注:在leetcode平臺上Math.max
要寫成_.max
(ps:第二週,第二天)