问题描述

提示:求一颗二叉搜索树的高度

给一个BST求其高度


难点分析:

提示:这里直接递归就好

递归的思路是每次把当前节点当成子树,求其左分支和右分支的最大高度,就这样递归下去,得到其子树的累加和,最后的左子树和右子树中累加和最高的就是BST的高度


代码:

提示:这里也可以用栈或者线性表来替代一下

import java.util.*;public class Lab25_01 {public static void main(String[] args) {BSTWithHeight<String> tree = new BSTWithHeight<>();System.out.print("The height of an empty tree is " + tree.height());tree.insert("Green");System.out.print("\nThe height of the tree with one node is " + tree.height());tree.insert("Red");System.out.print("\nThe height of the tree with two nodes is " + tree.height());Scanner input = new Scanner(System.in);System.out.print("\nEnter six strings: ");for (int i = 0; i < 6; i++) {String s = input.next();tree.insert(s.trim());}System.out.print("The height of tree is " + tree.height());BSTWithHeight<String> tree1 = new BSTWithHeight<>(new String[]{"Tom", "George", "Jean", "Jane", "Kevin", "Peter", "Susan","Jen", "Kim", "Michael", "Michelle"});System.out.print("\nThe height of tree1 is " + tree1.height());BSTWithHeight<Integer> tree2 =new BSTWithHeight<>(new Integer[]{50, 45, 35, 48, 59, 51, 58});
//        BSTWithHeight<Integer> tree2 =
//                new BSTWithHeight<>(new Integer[]{50, 45, 59, 35, 48, 47, 46});int temp = tree2.height();System.out.print("\nThe height of tree2 is " + temp);}
}interface Tree<E> extends Collection<E> {/*** Return true if the element is in the tree*/public boolean search(E e);/*** Insert element o into the binary tree* Return true if the element is inserted successfully*/public boolean insert(E e);/*** Delete the specified element from the tree* Return true if the element is deleted successfully*/public boolean delete(E e);/*** Get the number of nodes in the tree*/public int getSize();/*** Inorder traversal from the root*/public default void inorder() {}/*** Postorder traversal from the root*/public default void postorder() {}/*** Preorder traversal from the root*/public default void preorder() {}@Override/** Return true if the tree is empty */public default boolean isEmpty() {return size() == 0;};@Overridepublic default boolean contains(Object e) {return search((E) e);}@Overridepublic default boolean add(E e) {return insert(e);}@Overridepublic default boolean remove(Object e) {return delete((E) e);}@Overridepublic default int size() {return getSize();}@Overridepublic default boolean containsAll(Collection<?> c) {// Left as an exercisereturn false;}@Overridepublic default boolean addAll(Collection<? extends E> c) {// Left as an exercisereturn false;}@Overridepublic default boolean removeAll(Collection<?> c) {// Left as an exercisereturn false;}@Overridepublic default boolean retainAll(Collection<?> c) {// Left as an exercisereturn false;}@Overridepublic default Object[] toArray() {// Left as an exercisereturn null;}@Overridepublic default <T> T[] toArray(T[] array) {// Left as an exercisereturn null;}
}class BST<E> implements Tree25_02<E> {protected TreeNode<E> root;protected int size = 0;protected Comparator<E> c;/*** Create a default BST with a natural order comparator*/public BST() {this.c = new Comparator<E>() {public int compare(E e1, E e2) {return ((Comparable<E>) e1).compareTo(e2);}};}/*** Create a BST with a specified comparator*/public BST(Comparator<E> c) {this.c = c;}/*** Create a binary tree from an array of objects*/public BST(E[] objects) {this();for (int i = 0; i < objects.length; i++)add(objects[i]);}@Override/** Returns true if the element is in the tree */public boolean search(E e) {TreeNode<E> current = root; // Start from the rootwhile (current != null) {if (c.compare(e, current.element) < 0) {current = current.left;} else if (c.compare(e, current.element) > 0) {current = current.right;} else // element matches current.elementreturn true; // Element is found}return false;}@Override/** Insert element e into the binary tree* Return true if the element is inserted successfully */public boolean insert(E e) {if (root == null)root = createNewNode(e); // Create a new rootelse {// Locate the parent nodeTreeNode<E> parent = null;TreeNode<E> current = root;while (current != null)if (c.compare(e, current.element) < 0) {parent = current;current = current.left;} else if (c.compare(e, current.element) > 0) {parent = current;current = current.right;} elsereturn false; // Duplicate node not inserted// Create the new node and attach it to the parent nodeif (c.compare(e, parent.element) < 0)parent.left = createNewNode(e);elseparent.right = createNewNode(e);}size++;return true; // Element inserted successfully}protected TreeNode<E> createNewNode(E e) {return new TreeNode<>(e);}@Override/** Inorder traversal from the root */public void inorder() {inorder(root);}/*** Inorder traversal from a subtree*/protected void inorder(TreeNode<E> root) {if (root == null) return;inorder(root.left);System.out.print(root.element + " ");inorder(root.right);}@Override/** Postorder traversal from the root */public void postorder() {postorder(root);}/*** Postorder traversal from a subtree*/protected void postorder(TreeNode<E> root) {if (root == null) return;postorder(root.left);postorder(root.right);System.out.print(root.element + " ");}@Override/** Preorder traversal from the root */public void preorder() {preorder(root);}/*** Preorder traversal from a subtree*/protected void preorder(TreeNode<E> root) {if (root == null) return;System.out.print(root.element + " ");preorder(root.left);preorder(root.right);}/*** This inner class is static, because it does not access* any instance members defined in its outer class*/public static class TreeNode<E> {protected E element;protected TreeNode<E> left;protected TreeNode<E> right;public TreeNode(E e) {element = e;}}@Override/** Get the number of nodes in the tree */public int getSize() {return size;}/*** Returns the root of the tree*/public TreeNode<E> getRoot() {return root;}/*** Returns a path from the root leading to the specified element*/public ArrayList<TreeNode<E>> path(E e) {ArrayList<TreeNode<E>> list =new ArrayList<>();TreeNode<E> current = root; // Start from the rootwhile (current != null) {list.add(current); // Add the node to the listif (c.compare(e, current.element) < 0) {current = current.left;} else if (c.compare(e, current.element) > 0) {current = current.right;} elsebreak;}return list; // Return an array list of nodes}@Override/** Delete an element from the binary tree.* Return true if the element is deleted successfully* Return false if the element is not in the tree */public boolean delete(E e) {// Locate the node to be deleted and also locate its parent nodeTreeNode<E> parent = null;TreeNode<E> current = root;while (current != null) {if (c.compare(e, current.element) < 0) {parent = current;current = current.left;} else if (c.compare(e, current.element) > 0) {parent = current;current = current.right;} elsebreak; // Element is in the tree pointed at by current}if (current == null)return false; // Element is not in the tree// Case 1: current has no left childif (current.left == null) {// Connect the parent with the right child of the current nodeif (parent == null) {root = current.right;} else {if (c.compare(e, parent.element) < 0)parent.left = current.right;elseparent.right = current.right;}} else {// Case 2: The current node has a left child// Locate the rightmost node in the left subtree of// the current node and also its parentTreeNode<E> parentOfRightMost = current;TreeNode<E> rightMost = current.left;while (rightMost.right != null) {parentOfRightMost = rightMost;rightMost = rightMost.right; // Keep going to the right}// Replace the element in current by the element in rightMostcurrent.element = rightMost.element;// Eliminate rightmost nodeif (parentOfRightMost.right == rightMost)parentOfRightMost.right = rightMost.left;else// Special case: parentOfRightMost == currentparentOfRightMost.left = rightMost.left;}size--; // Reduce the size of the treereturn true; // Element deleted successfully}@Override/** Obtain an iterator. Use inorder. */public Iterator<E> iterator() {return new InorderIterator();}// Inner class InorderIteratorprivate class InorderIterator implements Iterator<E> {// Store the elements in a listprivate ArrayList<E> list =new ArrayList<>();private int current = 0; // Point to the current element in listpublic InorderIterator() {inorder(); // Traverse binary tree and store elements in list}/*** Inorder traversal from the root*/private void inorder() {inorder(root);}/*** Inorder traversal from a subtree*/private void inorder(TreeNode<E> root) {if (root == null) return;inorder(root.left);list.add(root.element);inorder(root.right);}@Override/** More elements for traversing? */public boolean hasNext() {if (current < list.size())return true;return false;}@Override/** Get the current element and move to the next */public E next() {return list.get(current++);}@Override // Remove the element returned by the last next()public void remove() {if (current == 0) // next() has not been called yetthrow new IllegalStateException();delete(list.get(--current));list.clear(); // Clear the listinorder(); // Rebuild the list}}@Override/** Remove all elements from the tree */public void clear() {root = null;size = 0;}
}// BEGIN REVEL SUBMISSION
class BSTWithHeight<E> extends BST25_15<E> {/*** Create a default BST with a natural order comparator*/public BSTWithHeight() {super();}/*** Create a BST with a specified comparator*/public BSTWithHeight(Comparator<E> c) {super(c);}/*** Create a binary tree from an array of objects*/public BSTWithHeight(E[] objects) {super(objects);}/*** Returns the height of this binary tree.*/public int height() {return height(root);}private int height(TreeNode<E> root) {// WRITE YOUR CODE HEREif (root == null) return -1;return Math.max(height(root.left), height(root.right)) + 1;}
}
// END REVEL SUBMISSION

java黑皮书25.1----(树的高度)相关推荐

  1. java黑皮书25.18-19----(压缩与解压),带界面,概念版

    问题描述 提示:运用霍夫曼编码压缩 实现压缩与解压缩 难点分析: 提示:我们自带了Huffman编码 这里思路是1.读取文件到内存中: 2.调用霍夫曼编码方法将文件压缩成霍夫曼编码及其解码表 3.将解 ...

  2. Java黑皮书课后题第10章:**10.25(新的字符串split方法)String类中的split方法会返回一个字符串数组,该数组是由分隔符分隔开的子串构成的

    Java黑皮书课后题第10章:**10.25(新的字符串split方法) 题目 代码 运行实例 题目 代码 public class Test25 {public static String[] sp ...

  3. java建树_JAVA实现通过中序遍历和后序遍历序列建树,并求树的高度,用层次遍历做验证...

    作为例子的树长这样: package bstpractice; import java.util.ArrayList; import java.util.Arrays; import java.uti ...

  4. 【Java数据结构】BST树(二叉搜索树)总结03(求BST树高度,求BST树节点个数)

    二叉树总结:入口 二叉树的基本操作: 1.插入,删除 操作 2.前.中.后序遍历,层序遍历 3.求BST树高度,求BST树节点个数 4.返回中序遍历第k个节点的值 5.判断一个二叉树是否是BST树,判 ...

  5. Java数据结构与算法——树(基本概念,很重要)

    声明:码字不易,转载请注明出处,欢迎文章下方讨论交流. 有网友私信我,期待我的下一篇数据结构.非常荣幸文章被认可,也非常感谢你们的监督. 前言:Java数据结构与算法专题会不定时更新,欢迎各位读者监督 ...

  6. java磁盘读写b 树_原来你是这样的B+树

    前言 B+树是目前最常用的一种索引数据结构,通常用于数据库和操作系统的文件系统中,本文就网上的知识点与个人理解结合分享,如有错误,欢迎探讨及指正. 定义 B+树是B树的一种变形形式,B+树上的叶子结点 ...

  7. Java黑皮书课后题第10章:10.2(BMI类)将下面的新构造方法加入BMI类中

    Java黑皮书课后题第10章:10.2(BMI类)将下面的新构造方法加入BMI类中 题目 程序说明 题目槽点 代码:Test2_BMI.java 运行实例 题目 程序说明 Test2_BMI.java ...

  8. Java黑皮书课后题第9章:**9.12(几何:交点)假设两条线段相交。第一条线段的两个端点是(x1, y1)和(x2, y2),第二条线段的两个端点是(x3, y3)和(x4, y4)

    Java黑皮书课后题第9章:**9.12(几何:交点)假设两条线段相交.第一条线段的两个端点是(x1, y1)和(x2, y2),第二条线段的两个端点是(x3, y3)和(x4, y4) 题目 破题 ...

  9. Java黑皮书课后题第1章:*1.11(人口估算)编写一个程序,显示未来5年的每年人口数。假设当前的人口是312 032 486,每年有365天

    Java黑皮书课后题第1章:*1.11(人口估算) 题目 题目描述 破题 代码块 方法评析 为什么print函数内的表达式不能分开 修改日志 题目 题目描述 *1.11(人口估算)编写一个程序,显示未 ...

最新文章

  1. python怎么继承_Python: 如何继承str/string?
  2. 预写式日志(Write-Ahead Logging (WAL))
  3. CTFshow 命令执行 web74
  4. python将字典作为参数传入函数
  5. 用AJAX技术聚合RSS
  6. 昨天,美团程序员的年终奖金可能没了!
  7. 迅雷 故意限速_故意记录的价值
  8. #pragma comment (lib, ws2_32.lib) 调用报错
  9. 教你划分必要开支和非必要开支
  10. Can not set java.util.Date field *** to java.time.LocalDateTime解决办法
  11. toms 尺寸 shoes or boots finds
  12. App渗透中常见的加密与解密
  13. Redis过期策略---实现原理
  14. WebBrowser查看版本
  15. NOAA(美国海洋和大气管理局)气象数据获取与POI点数据获取
  16. 夏影 ~あの飞行机云を超えた、その先へ~
  17. 串口转以太网模块:WIZ105SR配置及测试(一)
  18. windows 任务管理器 启动
  19. 声纹识别demo_声纹识别 · JD NeuHub API Documents
  20. mysql定时备份数据库

热门文章

  1. 伯克利博士『机器学习工程』大实话;AI副总裁『2022 ML就业市场』分析;半导体创业公司大列表;大规模视频人脸属性数据集;前沿论文 | ShowMeAI资讯日报
  2. linux查看逻辑卷lvlg,Linux LVM逻辑卷
  3. 投资经理,软件与互联网产品经理一个新去向?
  4. ? PHP WBEM
  5. JDK17遇到报错 module java.base does not “opens java.util“ to unnamed module 问题解决
  6. 使用Linux时ifconfig查看没有ens33,找不到虚拟机的ip地址,连不上网络,也没办法连接xshell?解决方式
  7. 使input文本框不可编辑的3种方法
  8. 重要性采样Importance Sampling
  9. 首届服务网格峰会明日开幕
  10. 离散余弦变换(Discrete Cosine Transform)