标题: | Construct Binary Tree from Inorder and Postorder Traversal |
通过率: | 26.7% |
难度: | 中等 |
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
前面做过一个已经前序和中序求二叉树,本题是一直中序和后续求二叉树道理一样
前序的第一个值一定是树的root,那么后序的最后一个值一定是树的root,
具体看代码:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode buildTree(int[] inorder, int[] postorder) { 12 if(inorder.length==0||postorder.length==0)return null; 13 TreeNode root=new TreeNode(postorder[postorder.length-1]); 14 int i=0; 15 for(;i<inorder.length;i++){ 16 if(inorder[i]==postorder[postorder.length-1])break; 17 } 18 int [] new_pos_left,new_pos_right,new_in_left,new_in_right; 19 if(i<postorder.length){ 20 new_in_left=new int[i]; 21 System.arraycopy(inorder, 0, new_in_left, 0, i); 22 new_pos_left=new int [i]; 23 System.arraycopy(postorder, 0, new_pos_left, 0, i); 24 root.left=buildTree(new_in_left,new_pos_left); 25 26 new_in_right=new int [inorder.length-i-1]; 27 System.arraycopy(inorder, i+1, new_in_right, 0, inorder.length-i-1); 28 new_pos_right=new int [postorder.length-i-1]; 29 System.arraycopy(postorder, i, new_pos_right, 0, postorder.length-i-1); 30 root.right=buildTree(new_in_right,new_pos_right); 31 } 32 return root; 33 } 34 }