21xrx.com
2025-03-29 19:09:57 Saturday
文章检索 我的文章 写文章
「C++二叉树代码」- 实现二叉树数据结构的C++代码
2023-07-02 13:09:16 深夜i     7     0
C++ 二叉树 数据结构 实现 代码

二叉树是计算机科学中广泛使用的一种数据结构,它由节点组成,每个节点包含一个数据元素,以及指向左子树和右子树的指针。二叉树的形状可以通过调整节点指针来改变,因此它具有灵活性。

在C++中,可以使用类来实现二叉树数据结构。下面是一个示例代码,展示了如何定义一个二叉树节点类和一个二叉树类,以及如何向二叉树中插入和查找元素。

// 定义二叉树节点类
class Node {
public:
  int value;
  Node* left;
  Node* right;
  Node(int v) : value(v), left(nullptr), right(nullptr) {}
};
// 定义二叉树类
class BinaryTree {
private:
  Node* root;
public:
  BinaryTree() : root(nullptr) {}
  // 向二叉树中插入节点
  void insert(int v) {
    if (root == nullptr) {
      root = new Node(v);
      return;
    }
    Node* current = root;
    while (true) {
      if (v < current->value) {
        if (current->left == nullptr) {
          current->left = new Node(v);
          return;
        }
        else
          current = current->left;
        
      }
      else {
        if (current->right == nullptr) {
          current->right = new Node(v);
          return;
        }
        else
          current = current->right;
        
      }
    }
  }
  // 在二叉树中查找元素
  bool contains(int v) {
    Node* current = root;
    while (current != nullptr) {
      if (v == current->value)
        return true;
      
      else if (v < current->value)
        current = current->left;
      
      else
        current = current->right;
      
    }
    return false;
  }
};

可以看到,这段代码中定义了两个类,Node和BinaryTree。Node类由一个整型value和指向左右子树的left和right指针组成,而BinaryTree类则具有根节点指针root,以及插入和查找元素的操作。

在insert操作中,如果根节点为空,则新建一个节点并将其作为根节点。否则,根据输入元素的大小不断遍历树的左右节点,直到找到一个合适的位置插入新节点。

在contains操作中,也是对树的遍历操作。根据输入元素的大小不断遍历树的左右节点,直到找到一个节点的值与输入值相同,或者遍历完整个树都找不到。

在实际应用中,二叉树可以用于排序、搜索、建立关系等多种场合,可以看出二叉树是一种高度实用的数据结构。通过上述示例代码的了解,希望对读者加深对C++二叉树实现的理解。

  
  

评论区

请求出错了