106. 从中序与后序遍历序列构造二叉树

思路:和105题一样,这次根节点在后续遍历的最后,找到它;之后在中序遍历里找到根节点。Arrays.copyOfRange()函数找出中序数组和后续数组的左右子树序列,递归,构成树,返回根节点。。。不细说了。感觉挺简单。
/**
* 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) {
if(inorder.length>0&&postorder.length>0)
{
TreeNode root=new TreeNode(postorder[postorder.length-1]);
int num=0;//根节点在中序遍历里的下标
for(int i=0;i<inorder.length;i++)
{
if(inorder[i]==root.val)
{
num=i;//左子树加上根节点有num+1个,左子树上面num个元素,这里注意
break;
}
}
int []inLeft=Arrays.copyOfRange(inorder,0,num);
int[] inRight=Arrays.copyOfRange(inorder,num+1,inorder.length);
int []postLeft=Arrays.copyOfRange(postorder,0,num);
int []postRight=Arrays.copyOfRange(postorder,num,postorder.length-1);
root.left=buildTree(inLeft,postLeft);
root.right=buildTree(inRight,postRight);
return root;
}
else
{
return null;
}
}
}

浙公网安备 33010602011771号