二叉树 BinaryTree.h

这是一个C++模板类实现的二叉树结构,包括插入元素、中序遍历、前序遍历和后序遍历等操作。类定义包含了一个节点结构TreeNode和二叉树结构BinaryTree,提供了构造函数、插入方法以及不同顺序的遍历方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifndef BINARYTREE_H
#define BINARYTREE_H

template<typename T>
class TreeNode
{
public:
  T element; // Element contained in the node
  TreeNode<T> * left; // Pointer to the left child
  TreeNode<T> * right; // Pointer to the right child

  TreeNode() // No-arg constructor
  {
    previous = NULL;
    next = NULL;
  }

  TreeNode(T element) // Constructor
  {
    this->element = element;
    left = NULL;
    right = NULL;
  }
};

template < typename T >
class BinaryTree
{
public:
  BinaryTree();
  BinaryTree(T elements[]);
  bool insert(T element);
  void inorder();
  void preorder();
  void postorder();
  int getSize();

private:
  TreeNode<T> * root;
  int size;
  void inorder(TreeNode<T> *root);
  void postorder(TreeNode<T> *root);
  void preorder(TreeNode<T> *root);
};

template < typename T >
BinaryTree<T>::BinaryTree()
{
  root = NULL;
  size = 0;
}

/* Insert element o into the binary tree
 * Return true if the element is inserted successfully
 * Return false if the element is already in the list
 */
template <typename T>
bool BinaryTree<T>::insert(T element)
{
  if (root == NULL)
    root = new TreeNode<T>(element); // Create a new root
  else
  {
    // Locate the parent node
    TreeNode<T> *parent = NULL;
    TreeNode<T> *current = root;
    while (current != NULL)
      if (element < current->element)
      {
        parent = current;
        current = current->left;
      }
      else if (element > current->element)
      {
        parent = current;
        current = current->right;
      }
      else
        return false; // Duplicate node not inserted

    // Create the new node and attach it to the parent node
    if (element < parent->element)
      parent->left = new TreeNode<T>(element);
    else
      parent->right = new TreeNode<T>(element);
  }

  size++;
  return true; // Element inserted
}

/* Inorder traversal */
template <typename T>
void BinaryTree<T>::inorder()
{
  inorder(root);
}

/* Inorder traversal from a subtree */
template <typename T>
void BinaryTree<T>::inorder(TreeNode<T> *root)
{
  if (root == NULL) return;
  inorder(root->left);
  cout << root->element << " ";
  inorder(root->right);
}

/* Postorder traversal */
template <typename T>
void BinaryTree<T>::postorder()
{
  postorder(root);
}

/** Inorder traversal from a subtree */
template <typename T>
void BinaryTree<T>::postorder(TreeNode<T> *root)
{
  if (root == NULL) return;
  postorder(root->left);
  postorder(root->right);
  cout << root->element << " ";
}

/* Preorder traversal */
template <typename T>
void BinaryTree<T>::preorder()
{
  preorder(root);
}

/* Preorder traversal from a subtree */
template <typename T>
void BinaryTree<T>::preorder(TreeNode<T> *root)
{
  if (root == NULL) return;
  cout << root->element << " ";
  preorder(root->left);
  preorder(root->right);
}

/* Get the number of nodes in the tree */
template <typename T>
int BinaryTree<T>::getSize()
{
  return size;
}

#endif

### C++ 二叉树实现及功能代码示例 以下是一个完整的 C++ 示例代码,展示了如何实现一个基于 `char` 类型节点的二叉树,并完成特定功能任务,包括输出 H 节点的左右孩子、求深度、宽度、节点数、叶子节点数以及释放二叉树。 #### binarytree.h ```cpp #ifndef BINARYTREE_H #define BINARYTREE_H #include <iostream> #include <queue> using namespace std; struct TreeNode { char data; TreeNode* left; TreeNode* right; TreeNode(char val) : data(val), left(nullptr), right(nullptr) {} }; class BinaryTree { private: TreeNode* root; int getDepth(TreeNode* node) const { if (node == nullptr) return 0; int leftDepth = getDepth(node->left); int rightDepth = getDepth(node->right); return max(leftDepth, rightDepth) + 1; } int getNodeCount(TreeNode* node) const { if (node == nullptr) return 0; return 1 + getNodeCount(node->left) + getNodeCount(node->right); } int getLeafNodeCount(TreeNode* node) const { if (node == nullptr) return 0; if (node->left == nullptr && node->right == nullptr) return 1; return getLeafNodeCount(node->left) + getLeafNodeCount(node->right); } void destroyTree(TreeNode* node) { if (node != nullptr) { destroyTree(node->left); destroyTree(node->right); delete node; } } public: BinaryTree() : root(nullptr) {} ~BinaryTree() { destroyTree(root); } void insertPreOrder(const vector<char>& preOrderList) { root = insertPreOrderHelper(preOrderList, 0, preOrderList.size()); } TreeNode* insertPreOrderHelper(const vector<char>& preOrderList, int index, int size) { if (index >= size || preOrderList[index] == '#') return nullptr; TreeNode* newNode = new TreeNode(preOrderList[index]); newNode->left = insertPreOrderHelper(preOrderList, 2 * index + 1, size); newNode->right = insertPreOrderHelper(preOrderList, 2 * index + 2, size); return newNode; } int getDepth() const { return getDepth(root); } int getNodeCount() const { return getNodeCount(root); } int getLeafNodeCount() const { return getLeafNodeCount(root); } int getWidth() const { if (root == nullptr) return 0; queue<TreeNode*> q; q.push(root); int maxWidth = 0; while (!q.empty()) { int currentWidth = q.size(); maxWidth = max(maxWidth, currentWidth); for (int i = 0; i < currentWidth; ++i) { TreeNode* node = q.front(); q.pop(); if (node->left != nullptr) q.push(node->left); if (node->right != nullptr) q.push(node->right); } } return maxWidth; } pair<TreeNode*, TreeNode*> getHChildren() const { if (root == nullptr) return {nullptr, nullptr}; queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* node = q.front(); q.pop(); if (node->data == 'H') { return {node->left, node->right}; } if (node->left != nullptr) q.push(node->left); if (node->right != nullptr) q.push(node->right); } return {nullptr, nullptr}; } void printTree() const { if (root == nullptr) { cout << "Empty Tree" << endl; return; } queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* node = q.front(); q.pop(); if (node != nullptr) { cout << node->data << " "; q.push(node->left); q.push(node->right); } else { cout << "# "; } } cout << endl; } }; #endif // BINARYTREE_H ``` #### main.cpp ```cpp #include "binarytree.h" int main() { vector<char> preOrderList = {'A', 'B', 'D', '#', '#', 'G', '#', '#', 'C', 'E', '#', '#', 'F', 'H', '#', '#'}; BinaryTree tree; tree.insertPreOrder(preOrderList); cout << "Print Tree: "; tree.printTree(); cout << "Depth of the tree: " << tree.getDepth() << endl; cout << "Number of nodes: " << tree.getNodeCount() << endl; cout << "Number of leaf nodes: " << tree.getLeafNodeCount() << endl; cout << "Width of the tree: " << tree.getWidth() << endl; pair<TreeNode*, TreeNode*> hChildren = tree.getHChildren(); if (hChildren.first != nullptr) { cout << "H's Left Child: " << (hChildren.first->data) << endl; } else { cout << "H's Left Child: NULL" << endl; } if (hChildren.second != nullptr) { cout << "H's Right Child: " << (hChildren.second->data) << endl; } else { cout << "H's Right Child: NULL" << endl; } return 0; } ``` --- ### 功能说明 1. **插入节点**:通过前序遍历的方式构建二叉树[^4]。 2. **计算深度**:递归地获取二叉树的最大深度[^1]。 3. **计算节点总数**:递归地统计所有节点的数量[^3]。 4. **计算叶子节点数**:递归地统计所有叶子节点的数量[^4]。 5. **计算宽度**:使用广度优先搜索(BFS)获取二叉树的最大宽度[^5]。 6. **获取 H 节点的左右孩子**:通过层次遍历找到 H 节点并返回其左右孩子[^1]。 7. **释放二叉树**:在析构函数中递归释放所有节点的内存[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值