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

原文地址:https://www.cnblogs.com/xiekai/p/3491577.html