Void函数用于计算指向的节点的权重

时间:2013-11-12 13:36:21

标签: c++ data-structures binary-tree binary-search-tree

我需要编写一个void函数,它可以计算每个子树中的节点数。 我读了很多示例代码,但它们都返回一个整数。我不知道如何使用非递归void函数来执行与int函数相同的函数。

这是我到目前为止所做的:

void computeWeight(treeNode<treeInfo> *p)
{
//compute the weight of the node pointed at by p    
//weight of a node is equal to the number of nodes in the correspodning subtree
if(p == NULL)
    p->info.weight = 0;
else
    p->info.weight = 1 + p->left->info.weight + p->right->info.weight;
//note that this is not a recursive function
}

这是treeInfo的结构:

struct treeInfo
{   
char symb;
int weight;
};

这是binaryTree.h,它是一个普通的二叉树标题

template<class Type>
struct treeNode
{
Type info;
treeNode<Type> *left;
treeNode<Type> *right;
};
template<class Type>
class treeIterator
{
protected:
treeNode<Type> *current;
stack<treeNode<Type>*> s;

public:
treeIterator(treeNode<Type> *p)
{
    current = NULL;

    while (p != NULL)
    {
        s.push(p);
        p = p->left;
    }

    if (!s.empty())
    {
        current = s.top();
        s.pop();
    }
}

treeIterator(const treeIterator<Type>& other)
{
    current = other.current;
    s = other.s;
}

Type& operator*() 
{   return current->info;  }


treeIterator<Type>& operator++()  //pre-increment operator
{
    if (current != NULL)
    {
        current = current->right;
        while (current != NULL)
        {
            s.push(current);
            current = current->left;
        }
        if (!s.empty())
        {
            current = s.top();
            s.pop();
        }
    }
    else
        cerr << "Error: treeIterator gets out of bound" << endl;

    return *this;
}

bool operator==(const treeIterator<Type>& other)
{  return current == other.current;  }

bool operator!=(const treeIterator<Type>& other)
{  return current != other.current;  }

};

template<class Type>
class binaryTree
{
protected:
treeNode<Type> *root;

public:
binaryTree()
{   root = NULL; }

binaryTree(const binaryTree<Type>& other);
~binaryTree();

const binaryTree<Type>& operator=(const binaryTree<Type>& other);

bool empty()
{   return root == NULL;  }

int height();
int nodeCount();
int leavesCount();

void inorderTraversal(void (*visit)(treeNode<Type> *));
void preorderTraversal(void (*visit)(treeNode<Type> *));
void postorderTraversal(void (*visit)(treeNode<Type> *));

void destroy();

treeIterator<Type> begin();
treeIterator<Type> end();

void print(int inc);
void buildTreeFromArray(Type a[], int n, Type nullSymbol);  

private:
treeNode<Type>* copyTree(const treeNode<Type> *other);
void destroy(treeNode<Type> *p);
int height(treeNode<Type> *p);
int nodeCount(treeNode<Type> *p);
int leavesCount(treeNode<Type> *p);
void inorder(treeNode<Type> *p, void (*visit)(treeNode<Type> *));
void postorder(treeNode<Type> *p, void (*visit)(treeNode<Type> *));

void printTree(const treeNode<Type> *p, int indent, int inc);
treeNode<Type>* buildTree(Type a[], int n, int i, Type nullSymbol);
};

template<class Type>
void binaryTree<Type>::preorderTraversal(void (*visit)(treeNode<Type> *p))
{
//implement a non-recrusive preorder traversal of the binary tree
stack<treeNode<Type>*> stack_tree;

stack_tree.push(root);
treeNode<Type> *p = root;
while(!stack_tree.empty())
{
    treeNode<Type>* temp = stack_tree.top();
    (*visit)(temp);

    stack_tree.pop();
    if(temp ->right)
        stack_tree.push(temp ->right);
    if(temp ->left)
        stack_tree.push(temp ->left);
}
} 

template<class Type>
treeNode<Type>* binaryTree<Type>::buildTree(Type a[], int n, int i, Type nullSymbol)
{
treeNode<Type> *p = NULL;

if (i < n && a[i] != nullSymbol)
{
    p = new treeNode<Type>;
    p->info = a[i];
    p->left = buildTree(a, n, 2*i+1, nullSymbol);
    p->right = buildTree(a, n, 2*(i+1), nullSymbol);
}

return p;
}

template<class Type>
void binaryTree<Type>::buildTreeFromArray(Type a[], int n, Type nullSymbol)
{
root = buildTree(a, n, 0, nullSymbol);
}

template<class Type>
void binaryTree<Type>::printTree(const treeNode<Type> *p, int indent, int inc)
{
if (p != NULL)
{
    printTree(p->right, indent+inc, inc);
    cout << setw(indent) << p->info << endl;
    printTree(p->left, indent+inc, inc);
}
}

template<class Type>
void binaryTree<Type>::print(int inc)
{
printTree(root, 4, inc);
}

template<class Type>
int binaryTree<Type>::height(treeNode<Type> *p) 
{
if (p == NULL)
    return 0;
int HL = height(p->left);
int HR = height(p->right);
if (HL >= HR)
    return 1+HL;
else
    return 1+HR;
}

template<class Type>
int binaryTree<Type>::height()  
{
return height(root);
}

template<class Type>
int binaryTree<Type>::nodeCount(treeNode<Type> *p)  
{
if (p == NULL)
    return 0;

return 1 + nodeCount(p->left) + nodeCount(p->right);
}

template<class Type>
int binaryTree<Type>::nodeCount()  
{
return nodeCount(root);
}

template<class Type>
int binaryTree<Type>::leavesCount(treeNode<Type> *p)  
{
if (p == NULL)
    return 0;

if (p->left == NULL && p->right == NULL)
    return 1;

return leavesCount(p->left) + leavesCount(p->right);
}

template<class Type>
int binaryTree<Type>::leavesCount()  
{
return leavesCount(root);
}

template<class Type>
void binaryTree<Type>::inorder(treeNode<Type> *p, void (*visit)(treeNode<Type> *))
{
if (p != NULL)
{
    inorder(p->left, visit);
    (*visit)(p);
    inorder(p->right, visit);
}
}

template<class Type>
void binaryTree<Type>::postorder(treeNode<Type> *p, void (*visit)(treeNode<Type> *))
{
if (p != NULL)
{
    postorder(p->left, visit);      
    postorder(p->right, visit);
    (*visit)(p);
}
}

template<class Type>
void binaryTree<Type>::inorderTraversal(void (*visit)(treeNode<Type> *))
{
inorder(root, visit);
}

template<class Type>
void binaryTree<Type>::postorderTraversal(void (*visit)(treeNode<Type> *))
{
postorder(root, visit);
}

template<class Type>
treeNode<Type>* binaryTree<Type>::copyTree(const treeNode<Type> *other)
{
    if (other == NULL)
    return NULL;

treeNode *p = new treeNode<Type>;
p->info = other->info;
p->left = copyTree(other->left);
p->right = copyTree(other->right);
}

template<class Type>
binaryTree<Type>::binaryTree(const binaryTree<Type>& other)
{
root = copyTree(other.root);
}

template<class Type>
const binaryTree<Type>& binaryTree<Type>::operator=(const binaryTree<Type>& other)
{
if (this != &other)
{
    destroy(root);
    root = copyTree(other.root);
}
}

template<class Type>
void binaryTree<Type>::destroy(treeNode<Type> *p)
{
if (p != NULL)
{
    destroy(p->left);
    destroy(p->right);
    delete p;
}
}


template<class Type>
void binaryTree<Type>::destroy()
{
destroy(root);
root = NULL;
}


template<class Type>
binaryTree<Type>::~binaryTree()
{
destroy(root);
}


template<class Type>
treeIterator<Type> binaryTree<Type>::begin()
{
return treeIterator<Type>(root);
}

template<class Type>
treeIterator<Type> binaryTree<Type>::end()
{
return treeIterator<Type>(NULL);
}

#endif

4 个答案:

答案 0 :(得分:0)

尝试类似:

 void computeWeight(treeNode<treeInfo> *p)
 {    
     std::list<treeNode<treeInfo>*> nodesToVisit;
     std::list<treeNode<treeInfo>*> nodesVisited;

     nodesToVisit.push_back(p);

     while(!nodesToVisit.empty())
     {
        treeNode<treeInfo>* parent = nodesToVisit.front();
        nodesToVisit.pop_front();


        if (parent->left != NULL)
           nodesToVisit.push_back(parent->left);

        if (parent->right != NULL)
           nodesToVisit.push_back(parent->right);

        nodesVisited.push_back(parent);
     }

     int numberOfNodes = nodesVisited.size();
  }

我不确定这个效率,但是它是一个void函数,用于计算每个子树中的节点数。

答案 1 :(得分:0)

允许是否递归?如果是这样,我想我可以这么简单:

void computeWeight(treeNode<treeInfo> *p) {
    //compute the weight of the node pointed at by p    
    //weight of a node is equal to the number of nodes in the corresponding sub-tree
    if(p) {
        // compute the weights of both children first
        computeWeight(p->left);
        computeWeight(p->right);

        // compute the weight of this node, taking into account its children
        int l_weight = p ? p->left->info.weight: 0;
        int r_weight = p ? p->right->info.weight: 0;
        p->info.weight = 1 + l_weight + r_weight;
    }

}

答案 2 :(得分:0)

首先,

if(p == NULL)
    p->info.weight = 0;

要求解决问题 - 您不能取消引用NULL

应该做的事情是这样的:

void computeWeight(treeNode<treeInfo> *p)
{
    if (p != NULL)
    {
        int leftWeight = p->left != NULL ? p->left->info.weight : 0;
        int rightWeight = p->right != NULL ? p->right->info.weight : 0;
        p->info.weight = 1 + leftWeight + rightWeight;
    }
}

并利用遍历确保首先计算子树的权重 由于它已经实现,您只需要选择正确的一个。


使用它应该看起来像这样

binaryTree<treeInfo> tree;
// ...  
// build the tree
// ...
tree.someTraversal(computeWeight);
// The weights are now computed.

答案 3 :(得分:0)

答案是

  • 使用递归和
  • 使用整数返回类型。

它将完全类似于(已存在的)binaryTree<Type>::height实现。

然后你可以在非递归的void返回函数中调用该函数,并对结果做任何事情。

void computeWeight(treeNode<treeInfo> *p) {
    int weight = getWeight(p);
    // Do something with it.
}

int getWeight(treeNode<treeInfo>* p) {
    return p == nullptr ? 0 : p->weight + getWeight(p->left) + getWeight(p->right);
}

当然,如果练习的特定目标是非递归地解决这个问题,那么该解决方案将不会这样做 - 您必须使用手动管理的堆栈来模拟递归。既然你有treeIterator我怀疑 - 迭代器使它既微不足道又毫无意义:

void computeWeight(treeNode<treeInfo> *p) {
    using iterator = treeIterator<treeInfo>;
    int weight const = std::accumulate(iterator{p}, iterator{nullptr}, 0,
            [](int acc, treeNode<treeInfo>* n) { return acc + n->weight; });
}

关于代码的一些注释。

代码使用C ++ 11,它应该是教学的标准,因为它使语言更容易和更安全,已经存在了两年,并且(在这里使用的程度)在所有现代编译器中实现。但是,了解编程课程的质量,很可能你不应该使用C ++ 11。在那种情况下,向老师抱怨(我的意思是!)并重写上面的代码 - 除了lambda之外,这些变化是微不足道的。更多关于这个:

我的代码使用算法(std::accumulate)而不是循环。人们一致认为这是ᴛʜᴇʀɪɢʜᴛᴛʜɪɴɢ™,因为它抽象出不相关的细节,应该在C ++的最前面和早期教授。但这又是理想主义的,也可能不是这样。它可以很容易地用循环代替:

int weight{};
for (iterator i{p}, end{}; i != end; ++i)
    weight += n->weight;
哇,那甚至更短。但由于种种原因,情况更糟,其中包括我们无法再weightconst这一事实。

最后,为什么我建议使用递归? - 因为它在概念上非常容易,而且几乎肯定更有效率。当然,理论上它容易出现堆栈溢出。但是,在实践中,它需要一个巨大的(或非常简并)树来触发堆栈溢出。这当然不是闻所未闻的,一个强大的通用库可以避免它,但对于大多数实际应用来说,它是完全可以接受的。