我们在第一篇中讲解了二叉树的构造和其相关的遍历算法。如果您还没有看第一篇文章,在这里我们在附上第一篇文章的地址https://blog.youkuaiyun.com/qzw5235641/article/details/85765750
今天是二叉树实现的第二篇
一、二叉树求节点个数算法
思路:递归计算二叉树左右子树的大小再加1
//求节点个数
public int count(BinaryTreeNode root){
if(root==null) return 0;
return count(root.left)+count(root.right)+1;
}
二、求二叉树的高度
//求高度
public int height(BinaryTreeNode root){
if(root==null) return 0;
int l=height(root.left);
int r=height(root.right);
return l>r ? l+1:r+1;
}
三、查找元素是否在树里存在
思路:先查根节点在递归左子树,在递归右子树
//查找某个元素是否在树里,返回那个元素
public static BinaryTreeNode serch(int data,BinaryTreeNode root){
if(root==null){
return null;
}
//先查找根节点是否匹配
if(root.getObject()==data){
return root;
}
//在查找左子树是否匹配
BinaryTreeNode result = serch(data, root.left);
//如果在左子树没有查找到则去有字数查找
if(result==null){
result = serch(data, root.right);
}
return result;
}
//查找元素是否存在
public boolean isExist(int data,BinaryTreeNode root){
BinaryTreeNode serch = serch(data, root);
if(serch==null) return false;
return true;
}
四、查找最大元素
//查找二叉树中最大元素\
public int findMax(BinaryTreeNode root){
int max=0;
if(root!=null){
int rootval=root.Object;
int l = findMax(root.left);
int r=findMax(root.right);
if(l>r){
max=l;
}
else {
max=r;
if(rootval>max) {
max=rootval;
}
}
}
return max;
}