【问题标题】:traversing a binary tree in postorder method在后序方法中遍历二叉树
【发布时间】:2021-11-17 01:41:48
【问题描述】:

我是二叉树新手,我想遍历二叉树中的第2个节点但输出结果为随机数或无输出。

这里是驱动函数:

int main(){
   node *root, *num2;

   bt tree;

   root = new node;
   root->data = 12;
   root->left = num2;
   root->right = NULL;

   tree.root = root;

   num2 = new node;
   num2->data = 10;
   num2->right = NULL;
   num2->left =NULL;

   std::cout<<"Postorder: ";
   tree.postorder();
   std::cout<<"\n";

   return 0;
}

二进制遍历方法:

struct bt{
    node *root = nullptr;

    public:
        void postorder(){
            postorder_impl(root);
        }
        
        
    private:
        void postorder_impl(node *start){
            if(!start) return;
            postorder_impl(start->left);
            postorder_impl(start->right);
            std::cout << start->data <<  " ";
        }
    
};

【问题讨论】:

    标签: c++ algorithm binary-tree dsa


    【解决方案1】:

    当你写 root-&gt;left = num2; num2 时尚未初始化。所以它是内存中的随机地址。所以root-&gt;left(和start-&gt;leftpostorder(); 函数内)。因此,即使您将 num2 设置为有效节点,您仍将调用带有未定义地址的 postorder_impl(); 函数将是一个随机内存地址。

    在它前面加上num2 = new node;root-&gt;left = num2;

    【讨论】:

    • 成功了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-01-12
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2016-01-09
    • 2021-03-08
    • 2020-01-15
    相关资源
    最近更新 更多