From 56d9af976a6df55808ebf8e834ed6cac7bfc38e1 Mon Sep 17 00:00:00 2001 From: X-shuffle <53906918+X-shuffle@users.noreply.github.com> Date: Sun, 13 Jun 2021 20:30:46 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200106.=E4=BB=8E=E4=B8=AD?= =?UTF-8?q?=E5=BA=8F=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91=20go?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0106.从中序与后序遍历序列构造二叉树 go版本 --- ...序与后序遍历序列构造二叉树.md | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index ba2d46a1..600a38e0 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -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 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