Construct a special tree from given preorder traversal

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);
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值