[英]How to delete a binary tree
邏輯很簡單-遍歷根以后序結束,然后使節點為空。 下面是我編寫的用於刪除樹的所有節點(即刪除二叉樹)的代碼。
問題:實際的樹沒有被刪除。 我的意思是deleteTree(BTNode root)函數僅將root ref的所有值都設為null,而不是head的所有值。
tree.preorder();
tree.deleteTree();
tree.preorder();- this still prints all values of a tree
即使執行tree.deleteTree()之后,它也會打印樹中的所有節點。
有人可以幫我解決代碼中的錯誤嗎?
注意 :insert和preorder函數中沒有錯誤。 因此,您可以只關注deleteTree()代碼
package com.practice;
import java.util.LinkedList;
public class BinaryTree {
private BTNode head;
public void insert(int data){
BTNode n= new BTNode (data);
BTNode temp=null;
if(head==null){
head=n;
return;
}
else{
LinkedList q= new LinkedList();
q.addLast(head); //enque
while(!q.isEmpty()){
temp=(BTNode) q.removeFirst();
if( temp.getLeft() ==null){
temp.setLeft(n);
return;
}
else{
//enque
q.addLast( temp.getLeft());
}
if( temp.getRight() ==null){
temp.setRight(n);
return;
}
else{
//enque
q.addLast( temp.getRight());
}
}//while loop ends here
}
}//insert ends here
public void preorder(){
preorder(head);
}
private void preorder(BTNode head){
if(head==null){
return;
}
else{
System.out.println(head.getData());\
preorder(head.getLeft());
preorder(head.getRight());
}
}
public void deleteTree(){
deleteTreeInternal(this.head);
}
private void deleteTree(BTNode root){
if(root == null){
return ;
}
else{
deleteTreeInternal(root.getLeft());
deleteTreeInternal(root.getRight());
root=null;
}
}
}//class ends here
package com.practice;
public class BTNode {
private BTNode left;
private BTNode right;
private int data;
public BTNode(){
}
public BTNode(int data){
this.data=data;
this.left=null;
this.right=null;
}
public BTNode getLeft() {
return left;
}
public void setLeft(BTNode left) {
this.left = left;
}
public BTNode getRight() {
return right;
}
public void setRight(BTNode right) {
this.right = right;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
只需設置root=null;
C ++不是垃圾收集,而Java是。 在Java中,一旦對象不再對其具有任何引用,它將自動從內存中刪除。 如果垃圾回收對象的所有引用對象沒有其他引用,也將被刪除。 那一點解決了您的問題:如果root下的節點沒有任何外部引用,則將在root之后自動將其刪除。
在您的deleteTree()
函數中,將head=null;
//沒有其他的。
刪除另一個deleteTree(BTNode root)
函數,該函數deleteTree(BTNode root)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.