题目
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
找到根节点,递归构造即可
代码
public class ConstructBinaryTreeFromInorderAndPostorderTraversal { private int[] inorder; private int[] postorder; public TreeNode buildTree(int[] inorder, int[] postorder) { assert inorder != null && postorder != null; assert inorder.length == postorder.length; this.inorder = inorder; this.postorder = postorder; int N = inorder.length; return solve(0, N - 1, 0, N - 1); } private TreeNode solve(int lowOfInorder, int highOfInorder, int lowOfPostorder, int highOfPostorder) { if (lowOfInorder > highOfInorder) { return null; } TreeNode root = new TreeNode(postorder[highOfPostorder]); for (int i = lowOfInorder; i <= highOfInorder; ++i) { if (inorder[i] == postorder[highOfPostorder]) { root.left = solve(lowOfInorder, i - 1, lowOfPostorder, lowOfPostorder + i - 1 - lowOfInorder); root.right = solve(i + 1, highOfInorder, highOfPostorder - highOfInorder + i, highOfPostorder - 1); break; } } return root; } }
LeetCode | Construct Binary Tree from Inorder and Postorder Traversal,布布扣,bubuko.com
LeetCode | Construct Binary Tree from Inorder and Postorder Traversal
原文:http://blog.csdn.net/perfect8886/article/details/20229389