2016-05-27 63 views
-2

以下是C++中的一個簡單的二叉樹代碼,我試圖實現,但在運行代碼時這些值正在被替換。二叉樹實現 - 分支上的數字正在被替換

#include<iostream> 
using namespace std; 

class bst 
{ 
private: 
    struct node 
    { 
     int data; 
     node *left; 
     node *right; 
    }; 
public: 
    node *start = NULL; 

    node* create_node(node*p,int a) 
    { 

     if (p == NULL) 
     { 
      node *n1 = new node; 
      n1->data = a; 
      n1->left = NULL; 
      n1->right = NULL; 
      return n1; 
     } 

     else 
     { 
      if (a > p->data) 
      { 
       p->right = create_node(p->right, a); 
      } 
      else if(a < p->data) 
      { 
       p->left = create_node(p->left, a); 
      } 
     } 

    } 

}; 

int main() 
{ 
    bst l1; 
    int a[10] = { 12, 4, 3, 9, 6, 5, 10, 13, 34, 23 }; 
    l1.start=l1.create_node(l1.start,a[0]); 
    for (int i = 0; i < 10; i++) 
    { 
     l1.create_node(l1.start, a[i]); 
    } 
    return 0; 
} 

任何人都可以請指出我在哪裏出錯了。 當我進行Inorder遍歷時,我的輸出是10 12 23. 當我通過帶有斷點的代碼時,我看到每個分支下的數字被替換。

+1

是你的編譯器不給你關於警告/錯誤的變化缺少create_node的返回值? – kfsone

+0

你的'create_node'返回* what *,again?仔細查看代碼。如果你的編譯器*不是*給你一個類似於'main.cpp:44:5的警告:控制可能會到達非空函數的末尾',那麼你真的需要打開警告級別。如果它*給出了這個警告,那麼在完全理解它們的含義之後,修正它(和任何其他警告)*。 – WhozCraig

+0

我看不到這段代碼是否錯誤。我強烈懷疑你的inorder函數是錯誤的。我繼續測試代碼,它工作得很好。你能分享你的inorder代碼嗎? –

回答

0

我的中序功能是:

void printInorder(node* node) 
    { 
     if (node == NULL) 
      return; 


     printInorder(node->left); 

     printf("%d ", node->data); 

     printInorder(node->right); 
    } 

我發現了問題,使得它的工作是類似於Vallabh提出一些

if (a > p->data) 
      { 
       if (p->right == NULL) 
       { 
        p->right = create_node(p->right, a); 
       } 
       else 
       { 
        create_node(p->right, a); 
       } 
      }