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 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public TreeNode BuildTree(int[] inorder, int[] postorder) { 12 if (postorder.Length == 0) return null; 13 14 return DFS(postorder, 0, postorder.Length - 1, inorder, 0, inorder.Length - 1); 15 } 16 17 private TreeNode DFS(int[] postorder, int pStart, int pEnd, int[] inorder, int iStart, int iEnd) 18 { 19 if (pStart > pEnd) return null; 20 if (pStart == pEnd) return new TreeNode(postorder[pStart]); 21 22 var root = new TreeNode(postorder[pEnd]); 23 24 int i = iStart; 25 for (; i <= iEnd; i++) 26 { 27 if (inorder[i] == postorder[pEnd]) break; 28 } 29 30 root.left = DFS(postorder, pStart, pStart + i - iStart - 1, inorder, iStart, i - 1); 31 root.right = DFS(postorder, pStart + i - iStart, pEnd - 1, inorder, i + 1, iEnd); 32 33 return root; 34 } 35 }