V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  normalize  ›  全部回复第 1 页 / 共 1 页
回复总数  1
2019-09-07 21:47:11 +08:00
回复了 fenghuang 创建的主题 程序员 问大家一个面试题
//12(2(34,4(,5)),6(7,))
//没有测试太多
function treeNode(val) {
this.val = parseInt(val)
this.right = null
this.left = null
}

function stringToTree(str) {
var ary = [] //[1,2,3,4,null,5,6,7]
var re = /\d+/g
re.lastindex = 0
var match

for(var i = 0; i < str.length; i++) {
if(str[i] == ',' && str[i - 1] == '('){
ary.push(null)
}else if(str[i] == ')') {
if(str[i - 1] == ',') {
ary.push(null)
}

var preNode = ary.slice(-3)
ary = ary.slice(0, -3)

preNode[0].left = preNode[1]
preNode[0].right = preNode[2]
ary.push(preNode[0])

}else if(str[i] == '('){
continue
}else if(match = re.exec(str)) {
ary.push(new treeNode(match[0]))
i = match.index + match[0].length - 1
}
}

return ary[0]
}
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3352 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 10ms · UTC 11:45 · PVG 19:45 · LAX 03:45 · JFK 06:45
Developed with CodeLauncher
♥ Do have faith in what you're doing.