[leedcode 106] Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
/*    注释见上一题:已知前序和中序,求树
    关键点:
    1 定位每层的根节点
    2 计算好offset*/
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length!=postorder.length||inorder.length==0) return null;
        return getNode(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
    }
    TreeNode getNode(int[] inorder,int left1,int right1,int[] postorder,int left2,int right2){
        if(left1>right1) return null;
        if(left2>right2) return null;
        int temp=postorder[right2];
        int index=left1;
        for(;index<=right1;index++){
            if(inorder[index]==temp)break;
        }
        int len=index-left1;
        TreeNode node=new TreeNode(temp);
        node.left=getNode(inorder,left1,index-1,postorder,left2,left2+len-1);
        node.right=getNode(inorder,index+1,right1,postorder,left2+len,right2-1);
        return node;
        
    }
}

 

你可能感兴趣的:(binary)