繁体   English   中英

递归地在二叉树中插入节点?

[英]Inserting nodes in a Binary Tree recursively?

我试图递归地在二叉树中插入节点,但代码只执行根节点,它是左右子节点。 我正在努力弄清楚如何克服这一点。

我已经尝试过不同的实现,使用队列,进行级别顺序插入。 我相信问题是由于在我的主函数中我只用 root 调用,如果这是问题,我将如何用左右孩子调用。

主功能:

int main() {
    treenode* root = new treenode();
    for(int a = 1; a < 15; a++) {
            insert(root, a);
    }
    cout << "Height: " << height(root) << endl;
    cout << "Printed Tree: " << endl;
    for(int a = 0; a <= height(root); a++) {
        printGivenLevel(root, a); //Print every level
        cout << endl;
    }
    return 0;
}

这是我的插入功能:

void insert(treenode*& node, int val) {
    if(node == nullptr) {
        node = new treenode(val);
        return;
    }else{
        if(node->left == nullptr) {
            insert(node->left, val);
        }else{
            insert(node->right, val);
        }
    }
}

一个树节点有一个值,一个左孩子和右孩子:

struct treenode {
    //The value of the node
    int value;
    //Pointers to the left and right children
    treenode *left, *right;
    //Constructor with values;
    treenode(int val=0, treenode *l = nullptr, treenode *r = nullptr) : value(val), left(l), right(r) {};
};

我希望结果是这样的:

0

1 2

3 4 5 6

7 8 9 10 11 12 13 14

但我的实际输出仅为:

0

1 2

提前致谢

...但代码只做根节点,它是左右孩子。 我正在努力弄清楚如何克服这一点。

我发现您的 treenode::insert 中没有错误,您的问题可能出在您未显示的其他代码中。 例如,您没有提供“高度(根)”或“印刷树”信息。 我无法诊断他们。

我为各种想法提供了一些替代方案。 参见“dump()”和“height()”和“size()”。

注意:“dump()”不是前序、中序或后序,因为排序的输入会创建不平衡的树显示(它们是最坏情况下的不平衡)。 我发现这个显示器最容易查看。

也许以下内容可以帮助您诊断错误。 祝你好运。

注意“if(false) cout << ...”的使用。 这些是诊断输出,可以通过启用它们和/或将此类项目添加到您的代码中来提供一些见解。

你试过你的调试器了吗?


#include <chrono> //    short form names----vvvvvvv
typedef std::chrono::high_resolution_clock  HRClk_t; // std-chrono-hi-res-clk
typedef HRClk_t::time_point                 Time_t;  // std-chrono-hi-res-clk-time-point
typedef std::chrono::nanoseconds            NS_t;    // std-chrono-nanoseconds
using  namespace std::chrono_literals;   // suffixes like 100ms, 2s, 30us
using  std::chrono::duration_cast;

#include <iostream>
using std::cout, std::endl, std::flush;

#include <iomanip>
using std::setw;


namespace DTB
{

class treenode
{
  friend class T920_t;

  int value;               //The value of the node

  treenode *left, *right;   //Pointers to the left and right children

  //Constructor with values;
  treenode(int val=0, treenode *l = nullptr, treenode *r = nullptr)
     : value(val), left(l), right(r) { ctor('A'); };


  void ctor(char kar) {
     if (left) left->ctor(kar);
     {
        if(false) // diagnostic
           cout << "\n  ctor: " << "   " << kar
                << "  val: " << setw(3) << value << flush;
     }
     if(right) right->ctor(kar);
  }

  void insert ( treenode*& node, int val)
     {
        if(node == nullptr)
        {
           node = new treenode(val);
           if (false) node->dump(); // diagnostic
           return;
        }
        else
        {
           if(node->left == nullptr)
           {
              insert(node->left, val);
              if (false) node->dump(); // diagnostic
           }
           else
           {
              insert(node->right, val);
              if (false) node->dump(); // diaagnostic
           }
        }
     }

  int height(int lvl = 1)
      {
         static int maxHeight = 0;
         if (left)  left->height (lvl+1);
         if(right) right->height (lvl+1);
         if (lvl > maxHeight) maxHeight = lvl;
         return maxHeight;
      }

  int size()
     {
        int count = 1; // this element
        if (left) { count +=  left->size(); };
        if(right) { count += right->size(); }
        return count;
     }


  void dump(int lvl=0)
     {
        if (left)  left->dump (lvl+1);
        if(right) right->dump (lvl+1);
        {
           cout << "\n  " // << lvl
                << setw(3*lvl) << ' '
                << value << flush;
        }
     }

}; // class treenode
typedef treenode Node_t; // shorter name for user-defined-type



class T920_t
{
public:
   int operator()(int argc, char* argv[]) { return exec(argc, argv); }

private:

   int exec(int , char** )
      {
         int retVal = 0;
         Time_t start_ns = HRClk_t::now();

         Node_t* root = new Node_t();  // 1st node
         for(int v = 1; v < 21; ++v) { // 20 more
            root->insert(root, v);
         }

         cout << "\n\n  size : " << root->size()  // element count
              << " maxHeight : " << root->height()
              << endl;

         dumpAll(root);

         for(int v = 1; v < 11; ++v) { // 10 more
            root->insert(root, v);
         }

         cout << "\n\n  size : " << root->size()  // element count
              << " maxHeight : " << root->height()
              << endl;

         dumpAll(root);


         auto  duration_ns = duration_cast<NS_t>(HRClk_t::now() - start_ns).count();

         cout << "\n\n\n  T920_t::exec() duration   "
              << duration_ns << " ns  "
              << "    cpluplus vers : " <<  __cplusplus  << std::endl;

         return retVal;
      }

   void dumpAll (Node_t*& node)
      {
         cout << "\n  dumpAll(): ";
         node->dump();
         cout << endl;
      }

}; // class T920_t
} // namespace DTB

int main(int argc, char* argv[]) { return DTB::T920_t()(argc, argv); }

部分输出是:

  size : 21 maxHeight : 11

  dumpAll(): 
     1
        3
           5
              7
                 9
                    11
                       13
                          15
                             17
                                19
                                20
                             18
                          16
                       14
                    12
                 10
              8
           6
        4
     2
   0


  size : 31 maxHeight : 16

  dumpAll(): 
     1
        3
   ...

                 10
              8
           6
        4
     2
   0


  T920_t::exec() duration   271095 ns      cpluplus vers : 201703

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM