Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
题目解析:给一个中序遍历数组和一个后序遍历的数组,推导出它对应的二叉搜索树。
根据后序遍历的特点,后序遍历数组的最后一位是根节点的值,然后根据根节点的值去中序遍历数组中查找相应的值,在中序遍历数组中,根节点前边的是左子树的中序遍历情况,可以算出左子树的节点个数为s,相对应的在后序遍历数组中前s项就是左子树的后序遍历情况。然后根据使用递归,就可以还原出二叉搜索树。
例如:
中序遍历:9, 3, 15, 20, 7
后序遍历:9, 15, 7, 20, 3
3是整个BST的根节点,在中序遍历中,3之前的节点是左子树的节点,也就是只有一个9,相对应的在后序遍历中9就是左子树的后序遍历。
public class ConstructBSTFromInorderAndPostorderTraversal {
public TreeNode buildTree(int[] inorder, int[] postorder) {
List<Integer> postList = new ArrayList<>();
List<Integer> midList = new ArrayList<>();
for (int i : postorder) {
postList.add(i);
}
for (int i : inorder) {
midList.add(i);
}
return buildTree(midList, postList);
}
private TreeNode buildTree(List<Integer> midList, List<Integer> postList) {
if(postList.isEmpty() || midList.isEmpty())
return null;
int value = postList.get(postList.size() - 1);
TreeNode root = new TreeNode(value);
int len = midList.indexOf(value);
root.left = buildTree(midList.subList(0, len), postList.subList(0, len));
root.right = buildTree(midList.subList(len+1, midList.size()), postList.subList(len, midList.size()-1));
return root;
}
}