package tree;
public class Construct {
/**
*
* Construct a special tree from given preorder traversal
Given an array ‘pre[]‘ that represents Preorder traversal of a spacial binary
tree where every node has either 0 or 2 children. One more array ‘preLN[]‘ is
given which has only two possible values ‘L’ and ‘N’. The value ‘L’ in ‘preLN[]‘
indicates that the corresponding node in Binary Tree is a leaf node and value ‘N’ indicates
that the corresponding node is non-leaf node. Write a function to construct the tree from the
given two arrays.
Source: Amazon Interview Question
Example:
Input: pre[] = {10, 30, 20, 5, 15}, preLN[] = {'N', 'N', 'L', 'L', 'L'}
Output: Root of following tree
10
/ \
30 15
/ \
20 5
* @param args
*/
public static int idx = 0;
public static TreeNode construct(int[] pre,char[] ln,int len){
if(idx==len) return null;
TreeNode root = new TreeNode(pre[idx]);
if(ln[idx]=='N'){
idx++;
root.left = construct(pre, ln, len);
root.right = construct(pre, ln, len);
return root;
}else{
idx++;
return root;
}
}
public static void print(TreeNode root){
if(root==null) return;
System.out.print(root.value+" ");
print(root.left);
print(root.right);
}
public static void printin(TreeNode root){
if(root==null) return;
printin(root.left);
System.out.print(root.value+" ");
printin(root.right);
}
public static void main(String[] args) {
int[] pre = {10, 30, 20, 5, 15};
char[] ln = {'N', 'N', 'L', 'L', 'L'};
TreeNode root = construct(pre, ln, pre.length);
print(root);
System.out.println();
printin(root);
}
}
Construct a special tree from given preorder traversal
最新推荐文章于 2014-07-01 19:49:27 发布