二叉树的中序遍历_Go 刷 leetcode从前序与中序遍历序列构造二叉树
今天為大家講解 LeetCode 第 105 題,是一道關(guān)于數(shù)組和樹(shù)的題目。
題目描述
根據(jù)一棵樹(shù)的前序遍歷與中序遍歷構(gòu)造二叉樹(shù)。
注意: 你可以假設(shè)樹(shù)中沒(méi)有重復(fù)的元素。
例如,給出
前序遍歷 preorder = [3,9,20,15,7] 中序遍歷 inorder = [9,3,15,20,7] 返回如下的二叉樹(shù):
3/ \
9 20
/ \
15 7
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
解題思路
preorder第一個(gè)元素為root,在inorder里面找到root,在它之前的為左子樹(shù)(長(zhǎng)stopIndex),之后為右子樹(shù)。preorder[1]到preorder[stopIndex]為左子樹(shù),之后為右子樹(shù),分別遞歸。
代碼實(shí)現(xiàn)
//go/**
?*?Definition?for?a?binary?tree?node.
?*?type?TreeNode?struct?{
?*?????Val?int
?*?????Left?*TreeNode
?*?????Right?*TreeNode
?*?}
?*/
func?buildTree(preorder?[]int,?inorder?[]int)?*TreeNode?{
????if?len(preorder)?==?0?{
????????return?nil
????}
????root?:=?&TreeNode{preorder[0],?nil,?nil}
????i?:=?0
????//?在inorder里root的下標(biāo)
????for?;?i?len(inorder);?i++?{
????????if?inorder[i]?==?preorder[0]?{
????????????break
????????}
????}
????//?root前的長(zhǎng)度,即左子樹(shù)的長(zhǎng)度
????stopIndex?:=?len(inorder[:i])+1
????root.Left?=?buildTree(preorder[1:stopIndex],?inorder[:i])
????root.Right?=?buildTree(preorder[stopIndex:],?inorder[i+1:])
????return?root
}
鄭重聲明:
所展示代碼已通過(guò) LeetCode 運(yùn)行通過(guò),請(qǐng)放心食用~
推薦閱讀
leetcode|被一道美團(tuán)面試題轉(zhuǎn)暈
站長(zhǎng) polarisxu
自己的原創(chuàng)文章
不限于 Go 技術(shù)
職場(chǎng)和創(chuàng)業(yè)經(jīng)驗(yàn)
Go語(yǔ)言中文網(wǎng)
每天為你
分享 Go 知識(shí)
Go愛(ài)好者值得關(guān)注
總結(jié)
以上是生活随笔為你收集整理的二叉树的中序遍历_Go 刷 leetcode从前序与中序遍历序列构造二叉树的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python2.7装饰器使用_pytho
- 下一篇: 信息学奥赛一本通_长乐一中老师演绎“奥赛