/*
* 自定义二叉树
*/
public class Tree {
Node<Integer> head;//二叉树头
public void add(Integer value) {
Node<Integer> node = new Node<>(value);
if(head == null) {
head = node;
}else {
Node<Integer> pNode = getNode(head,node);
if(pNode.value<node.value) {
pNode.right = node;
}else {
pNode.left = node;
}
}
}
//获取node 的对应插入位子
private Node<Integer> getNode(Node<Integer> pNode,Node<Integer> node) {
Node<Integer> curr = null;
while(pNode !=null) {
curr = pNode;
if(pNode.value<node.value) {
pNode = pNode.right;
}else {
pNode = pNode.left;
}
}
return curr;
}
//获取二叉树的深度
public int getHeight() {
return height(head,0);
}
private int height(Node<Integer> node,int height) {
if(node.left == null && node.right == null) {
return height;
}
int left = 0;
int right = 0;
if(node.left !=null) {
left = height(node.left,height+1);
}
if(node.right !=null) {
right = height(node.right,height+1);
}
height = Math.max(left, right);
return height;
}
}
public class TreeHeight {
//测试
public static void main(String[] args) {
// TODO Auto-generated method stub
Tree tree = new Tree();
tree.add(1);
tree.add(6);
tree.add(7);
tree.add(8);
tree.add(5);
tree.add(4);
tree.add(3);
tree.add(6);
tree.add(6);
tree.add(6);
int height = tree.getHeight();
System.out.println("高度:"+height);
}
}