版权声明:欢迎关注一起交流学习,个人 github: https://github.com/luoqifei https://blog.csdn.net/aa5305123/article/details/81940737
新建有序二叉树,left node 小于等于root,right node 大于等于root。并求二叉树的树高。
package dayscode;
import java.util.Scanner;
/**
* 插入new node到有序二叉树,获取二叉树最大树高
*/
public class BSTHeight {
static class Node {
Node left, right;
int data;
Node(int data) {
this.data = data;
left = right = null;
}
}
public static int getHeight(Node root) {
if (root == null) {
return 0;
}
int leftHeight = 0;//记录左子树的树高
int rightHeight = 0;//记录右子树树高
if (root.left != null) {//左子树不为空
leftHeight += getHeight(root.left) + 1;//实际就是左子树树高的累计,加上root节点,如果不加1,得到的就是最大子树的树高,不好root节点
}
if (root.right != null) {
rightHeight += getHeight(root.right) + 1;
}
return leftHeight >= rightHeight ? leftHeight : rightHeight;
}
public static Node insert(Node root, int data) {
if (root == null) {
return new Node(data);
} else {
Node cur;//定义一个游标,记录新节点
if (data <= root.data) {
cur = insert(root.left, data);//这个游标就是新子树的跟节点
root.left = cur;//让root 节点指向这个游标,将子树附着到root节点
} else {
cur = insert(root.right, data);
root.right = cur;
}
return root;
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
Node root = null;
while (T-- > 0) {
int data = sc.nextInt();
root = insert(root, data);
}
int height = getHeight(root);
System.out.println(height);
}
}