2018阿里巴巴实习生编程测验题

来源:互联网 发布:漳浦网络花店 编辑:程序博客网 时间:2024/05/29 16:29
题目:

对于一个由一位十进制整数构成的二叉树,如果深度不超过4,可以用一个三位十进制整数构成的数组表示,具体规则如下:


1, 百位数表示树的层次L,1<=L<=4;十位数表示在该层次中的位置P,1<=P<=8;个位数表示数值V。


2, 数组里,L一定是单增的,也就是说后一个数的L大于等于前一个数的L。


3, 对于同一个L,P也是单增的,就是说在L不变的情况下,后一个数的P大于等于前一个数的P。


例如:


[113, 215, 221]对应的树是:


   3


  /  \


5     1


现在要求这个树所有到叶子节点的路径和,对于[113, 215, 221] 这棵树,有两个路径3-5和 3-1,路径和是(3+5) + (3 + 1) = 12

分析:该题较为简单,对于一个按顺序排列的数组来说,建立一棵较为简单,不多说,上代码。

public class TreeRoute {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int n = scanner.nextInt();int location[] = new int[n];for(int i=0;i<n;i++){location[i] = scanner.nextInt();}int nodeVal[] = new int[n];int nodeLayer[] = new int[n];int nodeLocation[] = new int[n];for(int i=0;i<n;i++){//个位数是节点值nodeVal[i] = location[i]%10;//百位是层数nodeLayer[i] = location[i]/100;//十位是位置nodeLocation[i] = location[i]%100/10;}//保存每个节点被访问的次数,每个都初始化为零int root[] = new int[n];for(int i=0;i<n;i++){root[i] = 0;}//index指示的是寻找每个节点的父节点的索引,因此从头到尾值从n-1到0,每个值都只出现了一次int index = n-1;for(int i=n-1;i>=0;i--){while(index>=0){if(nodeLayer[index] == nodeLayer[i]-1 && Math.ceil(Float.valueOf(nodeLocation[i])/2) == nodeLocation[index]){//因为初始化为了0,因此对于叶子节点的父节点,此时的累加是加一if(root[i] == 0){root[index] += 1;}else{root[index] += root[i];}break;}else{index--;}}}//count 保存的是路径值的累加int count = 0;for(int i=n-1;i>=0;i--){if(root[i] == 0){//叶子节点只会被访问一次count+= nodeVal[i];}else{count += nodeVal[i]*root[i];}}System.out.println(count);scanner.close();}}

一切看代码吧!

0 0
原创粉丝点击