新建有序二叉树BST、求树的最大深度或高度

    新建有序二叉树,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);
    }
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值