2017-09-02 80 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