输出不打印?

时间:2017-09-02 08:39:16

标签: c++ c++11 c++14

从二进制树到树叶打印二进制树中的路径,但路径未打印,

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;
}

从二进制树到叶子打印二进制树中的路径但是路径没有打印,为什么会出现这个问题呢?

1 个答案:

答案 0 :(得分:1)

C ++中有一个非常基本的事实,即参数是由 value 传递的,修改函数内部的参数不会在函数范围之外修改它们。如果要在递归期间修改l和s,则需要将它们声明为 references ,由&amp;表示。在C ++中。因此,为了使程序输出某事,您需要进行的唯一更改是将l声明为引用。

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

输出: 这个二叉树的路径是:         1-> 2-> 4-> 8-> 2-> 5-> 3-> 3-> 3-> 3-> 7

相关问题