zoukankan      html  css  js  c++  java
  • FindMaxDeep

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package findmaxdeep;
    class Tree{
    int iData;
    Tree right;
    Tree left;
    }
    class Trees
    {
    Tree root=null;
    int maxdeep=0;
    public Trees(){}
    public void create() {

    for (int j = 0; j < 9; j++) {
    int i = (int) (Math.random() * 26);
    System.out.print(i + " ");
    insert(i);
    }
    System.out.print("\n");
    System.out.println("开始中序遍历");
    cOrder(root);
    System.out.print("\n");
    System.out.println("开始先序遍历");
    fOrder(root);
    System.out.print("\n");
    System.out.println("开始后续遍历");
    bOrder(root);
    }
    public void cOrder(Tree local) {
    if (local != null) {
    cOrder(local.left);
    System.out.print(" " + local.iData);
    cOrder(local.right);
    }
    }
    public void fOrder(Tree local) {
    if (local != null) {
    System.out.print(" " + local.iData);
    fOrder(local.left);
    fOrder(local.right);
    }
    }
    public void bOrder(Tree local) {
    if (local != null) {
    bOrder(local.left);
    bOrder(local.right);
    System.out.print(" " + local.iData);
    }
    }
    public void insert(int i) {
    Tree newTree = new Tree();
    newTree.iData = i;
    newTree.left=null;
    newTree.right=null;
    if (root == null) {
    root = newTree;
    return;
    }
    Tree current = root;
    Tree parent;
    while (true) {
    parent = current;
    if (i < current.iData) {
    current = current.left;
    if (current == null) {
    parent.left = newTree;
    return;
    }

    } else {
    current = current.right;
    if (current == null) {
    parent.right = newTree;
    return;
    }
    }
    }
    }
    public void findDeep(){
    if(root==null){return;}
    findeep(root,1);
    System.out.println("树的深度为:"+maxdeep);
    }
    public void getLongPath(){}
    int maxpath=0;
    public void getPath(){}
    public void findeep(Tree local,int ideep)
    {
    if(ideep>maxdeep){maxdeep=ideep;}
    if(local.left!=null||local.right!=null)
    {
    if(local.left!=null){
    findeep(local.left,ideep+1);
    }
    if(local.right!=null){
    findeep(local.right,ideep+1);
    }
    }

    }
    }


    /**
    *
    * 寻找树的深度
    * And
    * 寻找树最长的路径
    * 最长路径=左深+右深+1;
    * 递归寻找。
    * @author Administrator
    */
    public class FindMaxDeep {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    // TODO code application logic here
    Trees ts=new Trees();
    ts.create();
    ts.findDeep();
    }
    }

  • 相关阅读:
    org.apache.commons.io.FilenameUtils 常用的方法
    (转)同一服务器部署多个tomcat时的端口号修改详情
    JavaWeb中监听器+过滤器+拦截器区别、配置和实际应用
    idea tomcat服务器运行打印日志到控制台是乱码解决方案
    spring boot 添加整合ssl使得http变成https方法
    Fiddler 抓包工具总结
    一些概念
    观点汇总
    Spring 问题总结
    tomcat和jetty区别
  • 原文地址:https://www.cnblogs.com/xiekai/p/3491577.html
Copyright © 2011-2022 走看看