|
| 1 | +package main |
| 2 | + |
| 3 | +typeTreeNodestruct { |
| 4 | +Valint |
| 5 | +Left*TreeNode |
| 6 | +Right*TreeNode |
| 7 | +} |
| 8 | + |
| 9 | +/** |
| 10 | +根据中序和后续遍历结果,重建二叉树 |
| 11 | +后续遍历的最后一个元素,是二叉树的root节点 |
| 12 | +到中序数组中,root节点的位置,则左边用来递归创建左子树,右边用来递归创建右子树 |
| 13 | +*/ |
| 14 | + |
| 15 | +typeIndexstruct { |
| 16 | +indexint |
| 17 | +} |
| 18 | + |
| 19 | +funcbuildTree(inorder []int,postorder []int)*TreeNode { |
| 20 | +iflen(inorder)==0 { |
| 21 | +returnnil |
| 22 | +} |
| 23 | +//后续遍历的最后一个元素,是二叉树的root节点 |
| 24 | +rootIndex:=&Index{len(postorder)-1} |
| 25 | +returnbuildTreeR(inorder,postorder,0,len(postorder)-1,rootIndex) |
| 26 | +} |
| 27 | + |
| 28 | +funcbuildTreeR(inorder []int,postorder []int,startint,endint,rootIndex*Index)*TreeNode { |
| 29 | +ifstart>end { |
| 30 | +returnnil |
| 31 | +} |
| 32 | + |
| 33 | +rootValue:=postorder[rootIndex.index] |
| 34 | +root:=&TreeNode{rootValue,nil,nil} |
| 35 | +rootIndex.index-- |
| 36 | + |
| 37 | +ifstart==end { |
| 38 | +returnroot |
| 39 | +} |
| 40 | + |
| 41 | +//找到中序数组中,root节点的位置,则左边用来递归创建左子树,右边用来递归创建右子树 |
| 42 | +index:=0 |
| 43 | +fori:=start;i<=end;i++ { |
| 44 | +ifinorder[i]==rootValue { |
| 45 | +index=i |
| 46 | +break |
| 47 | +} |
| 48 | +} |
| 49 | + |
| 50 | +root.Right=buildTreeR(inorder,postorder,index+1,end,rootIndex) |
| 51 | +root.Left=buildTreeR(inorder,postorder,start,index-1,rootIndex) |
| 52 | + |
| 53 | +returnroot |
| 54 | +} |