根据一棵树的中序遍历与后序遍历构造二叉树。注意:
你可以假设树中没有重复的元素。例如,给出中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:3/ \9 20/ \15 7
解题思路
根据后序遍历的最后一个元素是父节点,在中序遍历中查找父节点,父节点的左边为左子树中序遍历的序列,右边为右子树中序遍历的序列,根据左右子树的长度,在后序遍历中找出左右子树的后序遍历的序列,再递归下一层。
代码
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public TreeNode buildTree(int[] inorder, int[] postorder) {return buildT(inorder,0,inorder.length-1,postorder,0,postorder.length-1);}public TreeNode buildT(int[] inorder,int inl,int inr, int[] postorder,int pol,int por) {if(inl>inr||pol>por) return null; TreeNode treeNode=new TreeNode(postorder[por]);int temp=0;while (inorder[inl+temp]!=postorder[por]) temp++;treeNode.left=buildT(inorder, inl, inl+temp-1, postorder, pol, pol+temp-1);treeNode.right=buildT(inorder,inl+temp+1,inr,postorder,pol+temp,por-1);return treeNode;}
}