Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路:后序遍历中最后一个节点为根节点,在中序遍历找到根节点的位置,从而确定左子树和右子树的数量。在后序遍历和中序遍中划分了左子树、右子树节点的值之后,递归调用,分别创建左右子树。
1 /** 2 * Definition for a binary tree node. 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 != postorder.length) { 13 return null; 14 } 15 return myBuildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); 16 } 17 private int findPosition(int[] inorder, int start, int end, int key) { 18 int i = 0; 19 for(i = start; i <= end; i++) { 20 if (inorder[i] == key) { 21 return i; 22 } 23 } 24 return -1; 25 } 26 27 private TreeNode myBuildTree(int[] inorder, int instart, int inend, int[] postorder, int pstart, int pend) { 28 if (instart > inend ) { 29 return null; 30 } 31 TreeNode root = new TreeNode(postorder[pend]); 32 int position = findPosition(inorder, instart, inend, postorder[pend]); 33 if (position == -1) { 34 return null; 35 } 36 root.left = myBuildTree(inorder, instart, position - 1, postorder, pstart, pstart + position - instart - 1); 37 root.right = myBuildTree(inorder, position + 1, inend, postorder, pstart + position - instart, pend - 1); 38 return root; 39 } 40 }

浙公网安备 33010602011771号