zoukankan      html  css  js  c++  java
  • 求二叉树中指定节点的深度

     1 package job.huawei;
     2 
     3 import java.util.Scanner;
     4 
     5 public class TreeHigh {
     6 
     7     /**
     8      * 输入字符串如a1b2c2d3e3f3g4构成一颗二叉树数字表示前一个字符所在的层,最多不超过9层
     9      * 求指定节点的深度
    10      */
    11     public static void main(String[] args) {
    12         // TODO Auto-generated method stub
    13         Scanner cin=new Scanner(System.in);
    14         String str=cin.next();
    15         String findChar=cin.next();
    16         cin.close();
    17         char tree[]=new char[512];
    18         createTree(str,tree);
    19         for(int i=0;i<findChar.length();i++){
    20             System.out.print(getNodeHigh(tree,str,findChar.charAt(i))+" ");
    21         }        
    22     }
    23     /**
    24      * 根据输入的字符串,顺序存储树
    25      * @param str
    26      * @param tree
    27      */
    28     public static void createTree(String str,char tree[]){
    29         int k=0,count=0,j=0;
    30         for(int i=1;i<str.length();i+=2){
    31             j=Integer.parseInt(String.valueOf(str.charAt(i)));//取某节点所在层
    32 
    33             if(i>1)
    34             {
    35                 count=str.charAt(i)!=str.charAt(i-2)?0:count+1;//判断是否在同一层,同一层则count+1,否则count=0
    36 
    37             }
    38             k=(int)Math.pow(2, j-1)+count;////计算节点的存储位置
    39 
    40             tree[k]=str.charAt(i-1);
    41         }
    42     }
    43     /**
    44      * 求指定节点在树中的深度
    45      * @param tree
    46      * @param str
    47      * @param x
    48      * @return
    49      */
    50     public static int getNodeHigh(char tree[],String str,char x) {
    51         int index=str.indexOf(String.valueOf(x));//判断该字符是否在树中,不在则直接返回
    52 
    53         if(index<0) return 0;
    54         
    55         int d=Integer.parseInt(String.valueOf(str.charAt(index+1))),level=0;//获取节点所在层次   
    56         
    57         while(2*d<tree.length&&tree[2*d]!=tree[0]){
    58             level++;
    59             d=2*d;
    60         }
    61         return level+1;
    62     }
    63 }
  • 相关阅读:
    php CURL 发送请求封装
    PHP AES加解密(兼容php5,php7)
    vscode jshint 报'import' is only available in ES6 (use 'esversion: 6'). (W119)错误
    vue-cli4 + TS构建新项目
    搭建vue项目
    分享一个自然语言汉语时间语义识别的工具类
    图像检索阶段性总结
    mysql常用操作
    javascript在页面head内动态插入style
    iScroll-5拉动刷新功能实现与iScroll-4上拉刷新的一点改进
  • 原文地址:https://www.cnblogs.com/cloudml/p/4377326.html
Copyright © 2011-2022 走看看