Wednesday, March 20, 2013

Construct Binary Tree from Inorder and Postorder Traversal


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


Find the root, using recursive.

Note:
You may assume that duplicates do not exist in the tree.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode buildTree(int[] a, int a1, int a2, int[] b, int b1, int b2){
        if(a1 > a2 || b1 > b2) return null;
        int rootval = b[b2];
        int posA = a1;
        while(posA <= a2){
            if(a[posA] == rootval) break;
            posA++;
        }
       
        TreeNode root = new TreeNode(rootval);
        int posB = b1 + posA - 1 - a1;
        TreeNode.left = buildTree(a,a1,posA-1,b, b1, posB);
        TreeNode.right = buildTree(a,posA+1,a2,b, posB+1,b2-1);
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(inorder.length == 0) return null;
        //return null;
        return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
       
    }
}

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/