本週在上週學習了二叉樹的基礎上,學習了一種二叉樹的特殊形式——二叉查找樹,又叫有序二叉樹、排序二叉樹。本章學習了兩種二叉查找樹的實現方法,以及兩種二叉查找樹的應用。html
addElement
:向樹中添加一個元素removeElement
:從樹中刪除一個元素removeAllOccurrences
:從樹中刪除所指定元素的任何存在removeMin
:刪除樹中的最小元素removeMax
:刪除樹中的最大元素findMin
:返回樹中的最小元素的引用findMax
:返回樹中的最大元素引用public void find(T element) { T result = null; BinaryTreeNode node = root; while (node != null) { if (element.CompareTo(node.getElement) > 0) { node = node.right; } else if (element.CompareTo(node.getElement) < 0) { node = node.left; } else { result = node.getElement; break; } } return result; }
public void find(T element) { return find(root, element); } private void find(BinaryTreeNode root, T element) { if (root == null) { return element; } int comparable = element.CompareTo(root.getElement); if (comparable > 0){ find(root.right,element); } else if (comparable < 0){ find(root.left,element); } else { return root.getElement; } }
null
,插入結點將會成爲新的左孩子。null
,則會繼續對左子樹進行遍歷,遍歷的同時進行比較操做。null
,插入結點將會成爲新的右孩子。null
,則會繼續對右子樹進行遍歷,遍歷的同時進行比較操做。null
便可。root
或父結點與之鏈接的指針設置爲空便可。root
指針指向被刪除結點的單支(左子樹或右子樹)LinkedBinaryTree
裏面的getHeight
方法中,可是我很是不理解爲何拋出的會是NullPointerException
。因而去查了一下會拋出NullPointerException
異常的緣由有哪些,通常有三種:字符串變量未初始化;接口類型的對象沒有用具體的類初始化;當一個對象的值爲空時,沒有判斷爲空。getHeight
的代碼,但背部疼痛診斷器是一顆滿樹,若是當我創建的樹不是一顆滿樹時,在gerHeight
調用getLeft
或者getRight
的時候,必定會出現指針爲空的狀況,而後就會拋出異常,因此我就將gerHeight
的方法改回來了。public int getHeight() { // if (root == null){ // return 0; // } // int leftChildHeight = getLeft().getHeight(); // int rightChildHeght = getRight().getHeight(); // // return Math.max(leftChildHeight,rightChildHeght) + 1; int result = height(root); return result; }
ExpreesionTree
中的PrintTree
方法能夠直接用做LinkedBinaryTree
中的toString
方法我就直接複製粘貼過來了,可是沒有改變相應的類型,在把全部的ExpreesionTreeOp類型改爲Integer類型後,程序就能完美地輸出樹了。上週考試無錯題。java
代碼行數(新增/累積) | 博客量(新增/累積) | 學習時間(新增/累積) | 重要成長 | |
---|---|---|---|---|
目標 | 5000行 | 30篇 | 400小時 | |
第一週 | 10/10 | 1/1 | 10/10 | |
第二週 | 246/366 | 2/3 | 20/30 | |
第三週 | 567/903 | 1/4 | 10/40 | |
第四周 | 2346/3294 | 2/6 | 20/60 | |
第五週 | 1343/4637 | 2/8 | 30/90 | |
第六週 | 1343/4637 | 2/8 | 20/110 | |
第七週 | 654/5291 | 1/9 | 25/135 |