2017-09-02 79 views
0

打印路徑不打印,輸出不打印?二叉樹從根到葉,但路徑

Paths in a Binary Search Tree from root to leaves 

      1 
    / \ 
    2  3 
/ \ /\ 
    4  5 6 7 
     /
     8 

。爲什麼是這個問題來請儘量給我的解決方案。二叉樹

#include<bits/stdc++.h> 
#include <stdio.h> 
#include <stdlib.h> 
using namespace std; 

bool flag = true; 

struct Node 
{ 
    int data; 
    struct Node* left; 
    struct Node* right; 
}; 

Node* newNode(int data) 
{ 
    Node* node = new Node; 
    node->data = data; 
    node->left = NULL; 
    node->right = NULL; 

    return(node); 
} 

list<string> getPath(Node *root, list<string> l, string s) 
{ 
    // Base Case 
    if (root==NULL) 
     return l; 

     if(root->left == NULL && root->right== NULL) { 
      if(!flag) { 
       s=s+"->"; 
      } 
      s=s + to_string(root->data); 
      l.push_back(s); 
     } 
     else { 
      if(!flag) { 
      s=s+"->"; 
      } 
     s=s + to_string(root->data); 
     } 

     flag = false; 
     if(root->left != NULL) { 
      getPath (root->left,l,s); 
     } 

     if(root->right != NULL) { 
      getPath (root->right,l,s); 
     } 

     return l; 
} 

list<string> binaryTreePaths(Node * root) 
{ 
    string s=""; 
    list<string> l; 
    return getPath(root, l, s); 
} 

//function for printing the elements in a list 
void showlist(list <string> g) 
{ 
    list <string> :: iterator it; 
    for(it = g.begin(); it != g.end(); ++it) 
     cout << '\t' << *it; 
    cout << '\n'; 
} 

int main() 
{ 
    Node *root = newNode(1); 
    root->left = newNode(2); 
    root->right = newNode(3); 
    root->left->left = newNode(4); 
    root->left->right = newNode(5); 
    root->right->left = newNode(6); 
    root->right->right = newNode(7); 
    root->left->left->right = newNode(8); 

    printf("Paths of this Binary Tree are:\n"); 
    list<string> s=binaryTreePaths(root); 

    showlist(s); 

    getchar(); 
    return 0; 
} 

打印幅面從根到葉,但路徑不打印,爲什麼這個問題呢?

+0

您是否嘗試調試它? 我會看看你的遞歸調用getpath() – Federico

+0

[''使用命名空間標準;'是一個不好的做法](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-認爲壞實踐)。停止使用它! – tambre

+0

不要包含,它是一個私有的非標準頭文件,不包含在內。你爲什麼包含C頭? – 2017-09-02 09:39:03

回答

1

在C++中存在一個非常基本的事實,即通過傳遞參數,並且修改函數內的參數不會在函數作用域之外修改它們。如果您想在遞歸過程中修改l和s,您需要聲明它們爲參考文獻,用C++中的&表示。因此,爲了使程序輸出東西需要進行的唯一更改是將l聲明爲引用。

list<string> getPath(Node *root, list<string>& l, string s) 

輸出:這個二叉樹 路徑是: 1-> 2-> 4-> 8 1-> 2-> 5 1-> 3-> 6 1-> 3-> 7

+0

是的,我錯過了引用的概念,感謝您的幫助。其實我期待1-> 2-> 4-> 8,1-> 2-> 5,1-> 3-> 6,1-> 3-> 7。 – Kamal

+0

在我的本地代碼中運行相同塊時,我在to_string fun()中遇到錯誤,爲什麼會發生這種情況? @leyanpan – Kamal

+0

什麼是錯誤?它適用於我的Visual Studio,儘管這可能不是一個非常具有代表性的編譯器。 – leyanpan