簡體   English   中英

二叉樹遍歷中的問題

[英]Problems in binary tree traversal

我正在嘗試實現按順序遍歷的二進制搜索樹。 我試圖互相打印一系列數字以對其進行測試。 看起來它的排序很好,但是有時它會打印重復的數字。 查看我的代碼的相關部分:

樹的類和方法:

 public class Tree {
Node root;

public Tree(){
root = null;
}


public Node add(Node n, int value){
if(n== null){
    n= new Node(value);
}else if(value < n.getValue()){
    n.addLeftNode(add(n.getLeft(),value));
}else if(value > n.getValue()){
    n.addRightNode(add(n.getRight(),value));
}

return n;
}

public static Node traverse(Node n){

Node result = new Node();

if(n != null){


    if(n.getLeft() != null){

        result = traverse(n.getLeft()); 
        System.out.println(result.getValue());                
    }

        result = n;
        System.out.println(result.getValue());      


    if(n.getRight() != null){     

        result = traverse(n.getRight());
        System.out.println(result.getValue());

    }

}
return result;
}
}

這是打印出來的內容:


0 0 1 1 3 4 4 5 6 7 7 8 10 11 12 12 12 15 15 15 15 15 15 15 16 18 18 20 21 22 22 22 22 23 27 28 28 28 29 34 35 43 43 43 43 43 43 43 44 45 45 55 56 59 66 75 75 75 75 75 75 76 76 76 78 88 89 89 90 90 90 98 98

有什么線索嗎? 我想這是遍歷的東西。 嘗試調試它,但是我仍然找不到問題。 如您所見,編號至少已排序。

當您向左或向右遍歷時,遍歷的調用將打印左/右節點。 您不必分別左右打印。

if(n != null){
    if(n.getLeft() != null){
        result = traverse(n.getLeft()); 
        // System.out.println(result.getValue());                
    }

    result = n;
    System.out.println(result.getValue()); // This prints the left and right via recursion into traverse(...)

    if(n.getRight() != null){     
        result = traverse(n.getRight());
        // System.out.println(result.getValue());
    }
}

遍歷方法應為:

void traverse(Node n) {
    if(n == null)
        return;

    traverse(n.getLeft());
    System.out.println(n.getValue());
    traverse(n.getRight());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM