21xrx.com
2025-04-28 13:56:38 Monday
文章检索 我的文章 写文章
C++实现二叉树建立的代码
2023-07-09 14:16:22 深夜i     --     --
C++ 二叉树 建立 代码 实现

二叉树是一种常用的数据结构,在计算机科学领域有着广泛的应用。C++是一种很流行的编程语言,用于实现二叉树建立的代码非常方便。

以下是C++实现二叉树建立的代码示例:

#include<iostream>
using namespace std;
//定义二叉树的节点
struct TreeNode
{
  int data;
  TreeNode* left;
  TreeNode* right;
};
// 二叉树节点的构造函数
TreeNode* NewNode(int data)
{
  TreeNode* node = new TreeNode();
  node->data = data;
  node->left = NULL;
  node->right = NULL;
  return node;
}
// 二叉树的插入函数
void Insert(TreeNode* &root, int data)
{
  if (root == NULL)
  {
    root = NewNode(data);
  }
  else if (data <= root->data)
  {
    Insert(root->left, data);
  }
  else
  {
    Insert(root->right, data);
  }
}
int main()
{
  // 创建一个空根节点root
  TreeNode* root = NULL;
  
  Insert(root, 10);
  Insert(root, 3);
  Insert(root, 20);
  Insert(root, 15);
  Insert(root, 30);
  cout<<"二叉树的节点为:"<<endl;
  cout<<" "<<root->data<<endl;
  cout<<"/  \\"<<endl;
  cout<<root->left->data<<"  "<<root->right->data<<endl;
  cout<<"  /  \\"<<endl;
  cout<<" "<<root->right->left->data<<"   "<<root->right->right->data<<endl;
  return 0;
}

上面的代码实现了一个简单的二叉树,通过插入节点的方式,将数据插入到二叉树中。首先定义一个二叉树节点的结构体,包含节点的数据、左右子树的指针。

之后定义了一个新节点的构造函数。用于创建新的二叉树节点,并初始化节点的数值和左右子树。

最后定义一个插入节点的函数,遍历二叉树的左右子树,找到适合的位置插入数据。如果树为空,则直接将数据放在根节点上,否则遍历左右子树,直到找到合适的位置插入数据。

在主函数中,定义一个空的根节点,依次将数据插入到二叉树中。最后通过输出的方式,展示了这棵二叉树的结构

总结来说,二叉树是一种常见的数据结构,可以通过C++语言实现二叉树的建立。在实现二叉树建立的代码时,需要对二叉树节点的结构体、新节点的构造函数和插入节点的函数进行定义。通过插入节点的方式,将数据逐一加入到二叉树中,形成一个完整的二叉树。

  
  

评论区