添加 0106.从中序与后序遍历序列构造二叉树 go版本

添加 0106.从中序与后序遍历序列构造二叉树 go版本
This commit is contained in:
X-shuffle
2021-06-13 20:30:46 +08:00
committed by GitHub
parent 8a01ff24e0
commit 56d9af976a

View File

@ -693,6 +693,70 @@ class Solution:
return root
```
Go
> 106 从中序与后序遍历序列构造二叉树
```go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func buildTree(inorder []int, postorder []int) *TreeNode {
if len(inorder)<1||len(postorder)<1{return nil}
//先找到根节点(后续遍历的最后一个就是根节点)
nodeValue:=postorder[len(postorder)-1]
//从中序遍历中找到一分为二的点,左边为左子树,右边为右子树
left:=findRootIndex(inorder,nodeValue)
//构造root
root:=&TreeNode{Val: nodeValue,
Left: buildTree(inorder[:left],postorder[:left]),//将后续遍历一分为二,左边为左子树,右边为右子树
Right: buildTree(inorder[left+1:],postorder[left:len(postorder)-1])}
return root
}
func findRootIndex(inorder []int,target int) (index int){
for i:=0;i<len(inorder);i++{
if target==inorder[i]{
return i
}
}
return -1
}
```
> 105 从前序与中序遍历序列构造二叉树
```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)<1||len(inorder)<1{return nil}
left:=findRootIndex(preorder[0],inorder)
root:=&TreeNode{
Val: preorder[0],
Left: buildTree(preorder[1:left+1],inorder[:left]),
Right: buildTree(preorder[left+1:],inorder[left+1:])}
return root
}
func findRootIndex(target int,inorder []int) int{
for i:=0;i<len(inorder);i++{
if target==inorder[i]{
return i
}
}
return -1
}
```
JavaScript