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);
}
}
Subscribe to:
Post Comments (Atom)
Manacher's Longest Palindromic Substring Algorithm
http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/
-
Suppose a bus is running on a loop route. It takes 10 mins for the bus to finish the route. If a guy arrives at a bus stop at uniformly rand...
-
Question: You are playing a card game with me. Suppose I shuffle a deck of 52 cards, then I show you the card one by one to you from top t...
-
Move Objects There are N objects kept in a row. The ith object is at position x_i. You want to partition them into K groups. You want ...
No comments:
Post a Comment