第六次数据结构作业 - 计算二叉树中结点值等于某给定值结点个数

题意如下:

已知二叉树采用二叉链表存储,其结点结构定义如下:

template<class T>   
struct BinTreeNode{
 T data;
 BinTreeNode<T> *lchild,*rchild;
};

编写计算二叉树中节点data值等于给定x值的结点个数算法,p指向二叉树的根节点,BinaryTree为二叉树类。函数原型为:

int BinaryTree::CountNode(BinTreeNode *p,T x);

分析:

这个题我本来想复习一下通过前序和中序建立二叉树,但是发现不能这样做,因为可能有多个相同的节点的值,所以最后采用的是利用二叉树前序遍历建立其中0代表空结点

之后我又犯了一个重大错误,在自己做的测试数据中,只进行了非0节点的前序遍历,但是没有考虑到0导致程序出错,这个算法那掌握还是不很好,需要以后多看多练

代码如下:

/*
测试数据:前序建立内容和要查找的结果
1 2 1  0 0 1 0 0 1 6 0 0 7 0 0
1
答案为4
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>

using namespace std;
const int maxn = 1000;

template<class T>
struct BinTreeNode
{
    T data;
    BinTreeNode<T>* lchild, * rchild;
    BinTreeNode()
    {
        lchild = rchild = NULL;
    }
    BinTreeNode(int dd):data(dd),lchild(NULL),rchild(NULL) {}
};
//编写计算二叉树中节点data值等于给定x值的结点个数算法,
//p指向二叉树的根节点,BinaryTree为二叉树类

template<class T>
class BinaryTree
{
public:
    int CountNode(BinTreeNode<T> *p,T x);
    void CreateTree(BinTreeNode<T>* & root)
    {
        T tmp;
        cin >> tmp;
        if(tmp == 0)
            root = NULL;
        else
        {
            root = new BinTreeNode<T>(tmp);
            CreateTree(root->lchild);
            CreateTree(root->rchild);
        }
    }
    void Postorder(BinTreeNode<T> *root)
    {
        if(root != NULL)
        {
            Postorder(root->lchild);
            Postorder(root->rchild);
            cout << root->data << " ";
        }
    }
    void Preorder(BinTreeNode<T> *root)
    {
        if(root != NULL)
        {
            cout << root->data << " ";
            Preorder(root->lchild);
            Preorder(root->rchild);
        }
    }
    void Inorder(BinTreeNode<T> *root)
    {
        if(root != NULL)
        {
            Inorder(root->lchild);
            cout << root->data <<" ";
            Inorder(root->rchild);
        }
    }

};
template<class T>
int BinaryTree<T>::CountNode(BinTreeNode<T> *p,T x)
{

    if(p != NULL)
    {
        if(p->data == x)
            return CountNode(p->lchild,x)+CountNode(p->rchild,x)+1;
        else
            return CountNode(p->lchild,x)+CountNode(p->rchild,x);
    }
    return 0;
}

int main()
{
    BinTreeNode<int> * root = NULL;
    BinaryTree<int> obj;
    obj.CreateTree(root);
    obj.Preorder(root);
    cout << endl;
    obj.Inorder(root);
    cout << endl;
    obj.Postorder(root);
    cout << endl;
    int x;
    cin >> x;
    cout << obj.CountNode(root,x) << endl;
    return 0;
}

posted @ 2017-10-25 21:02  pprp  阅读(2070)  评论(0编辑  收藏  举报