zoukankan      html  css  js  c++  java
  • 二叉树系列二:二叉树的C++表示

    为了表示二叉树,定义两个类:TreeNode和Tree,其中TreeNode class是对结点信息的抽象,它包括结点的数据域和分别指向左子树和右子树的指针域;Tree class是对二叉树的抽象,一个二叉树由一个根结点确定,所以其成员变量为一个根结点指针,此外它也抽象了二叉树的各种操作,包括二叉树的遍历等。它的C++基本实现如下:

    TreeNode class:

     1 /* TreeNode.h */
     2 #ifndef TREENODE_H
     3 #define TREENODE_H
     4 
     5 template<class T> class Tree;
     6 
     7 template<class T>
     8 class TreeNode
     9 {
    10     friend class Tree<T>;
    11 public:
    12     TreeNode()
    13     {
    14         leftChild = NULL;
    15         data = 0;
    16         rightChild = NULL;
    17     }
    18 private:
    19     TreeNode<T>* leftChild;
    20     T data;
    21     TreeNode<T>* rightChild;
    22 };
    23 
    24 #endif
    View Code

    Tree class:

     1 /* Tree.h */
     2 #ifndef TREE_H
     3 #define TREE_H
     4 
     5 #include "TreeNode.h"
     6 
     7 template<class T>
     8 class Tree
     9 {
    10 public:
    11     Tree();
    12     bool isEmpty();
    13     void PreOrder(TreeNode<T>* root);
    14     void MidOrder(TreeNode<T>* root);
    15     void PostOrder(TreeNode<T>* root);
    16 private:
    17     TreeNode<T>* root;
    18 };
    19 
    20 #endif
    View Code

    在随后的章节中,为了使表达更直观更简洁,将TreeNode和Tree中的成员变量的属性设为了public。

  • 相关阅读:
    random 模块
    re 模块
    正则表达式
    15. 3Sum
    253. Meeting Rooms II
    91. Decode Ways
    17. Letter Combinations of a Phone Number
    314. Binary Tree Vertical Order Traversal
    311. Sparse Matrix Multiplication
    311. Sparse Matrix Multiplication
  • 原文地址:https://www.cnblogs.com/sophia-yun/p/3144177.html
Copyright © 2011-2022 走看看