标签:技术 tco solution hashmap ret 图片 gen slice set
题目描述:根据一棵树的前序遍历与中序遍历构造二叉树。假设树中没有重复的元素。
今日学习:
1.复习二叉树遍历
2.复习map
3.搭建mediasoup-demo(websocket连接失败,原因没找到)
4.脚手架是为了减少因为想要减少重复工作而进行的重复工作
天使爆破组果然是小天使,题解一我想出来了,后续题解没有想到
题解1:
var buildTree = function(preorder, inorder) {
if(!preorder.length) return null
const node = new TreeNode(preorder[0])
const index = inorder.indexOf(preorder[0])
const inLeft = inorder.slice(0, index)
const inRight = inorder.slice(index + 1)
const preLeft = preorder.slice(1, index + 1)
const preRight = preorder.slice(index + 1)
node.left = buildTree(preLeft, inLeft)
node.right = buildTree(preRight, inRight)
return node
};
题解2:
//不用slice改用指针
var buildTree = (preorder, inorder) => {
return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1)
}
function helper(preorder, p_start, p_end, inorder, i_start, i_end) {
if (p_start > p_end) return null // preorder为空
let rootVal = preorder[p_start] // 根节点的值
let root = new TreeNode(rootVal) // 根节点
let mid = inorder.indexOf(rootVal) // 根节点在inorder的位置
let leftNum = mid - i_start // 左子树的节点数
root.left = helper(preorder, p_start + 1, p_start + leftNum, inorder, i_start, mid - 1)
root.right = helper(preorder, p_start + leftNum + 1, p_end, inorder, mid + 1, i_end)
return root
}
题解3:
//hashmap版
var buildTree = (preorder, inorder) => {
let map = new Map()
for (let i = 0; i < inorder.length; i++) {
map.set(inorder[i], i)
}
return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map)
}
function helper(preorder, p_start, p_end, inorder, i_start, i_end, map) {
if (p_start > p_end) return null // preorder为空
let rootVal = preorder[p_start] // 根节点的值
let root = new TreeNode(rootVal) // 根节点
let mid = map.get(rootVal) // 根节点在inorder的位置
let leftNum = mid - i_start // 左子树的节点数
root.left = helper(preorder, p_start + 1, p_start + leftNum, inorder, i_start, mid - 1, map)
root.right = helper(preorder, p_start + leftNum + 1, p_end, inorder, mid + 1, i_end, map)
return root
}
leetcode每日一题(2020-05-22):105. 从前序与中序遍历序列构造二叉树
标签:技术 tco solution hashmap ret 图片 gen slice set
原文地址:https://www.cnblogs.com/autumn-starrysky/p/12939573.html