本文共 1466 字,大约阅读时间需要 4 分钟。
下面是树类型题目需要用到的头文件tree.h,请包含在cpp文件中编译,而不是放在c文件中编译,比如查找树中两个节点的最低公共父结点的题common_parent_in_tree.cpp,编译它的方法是:
g++ -g common_parent_in_tree.cpp -o common_parent_in_tree
下面是tree.h的内容:
#include#include struct TreeNode{ int value; std::vector vec_children;};TreeNode* CreateTreeNode(int value){ TreeNode* pNode = new TreeNode(); pNode->value = value; return pNode;}void ConnectTreeNodes(TreeNode* pParent, TreeNode* pChild){ if(pParent != NULL){ pParent->vec_children.push_back(pChild); }}void PrintTreeNode(TreeNode* pNode){ if(pNode != NULL){ printf("value of this node is: %d\n", pNode->value); printf("its children is as the following"); std::vector ::iterator i = pNode->vec_children.begin(); while(i < pNode->vec_children.end()){ if(*i != NULL) printf("%d\t", (*i)->value); } printf("\n"); }else{ printf("this node is null.\n"); } printf("\n");}void PrintTree(TreeNode* pRoot){ PrintTreeNode(pRoot); if(pRoot != NULL){ std::vector ::iterator i = pRoot->vec_children.begin(); while(i < pRoot->vec_children.end()){ PrintTreeNode(*i); ++i; } }}void DestroyTree(TreeNode* pRoot){ if(pRoot != NULL){ std::vector ::iterator i = pRoot->vec_children.begin(); while(i < pRoot->vec_children.end()){ DestroyTree(*i); ++i; } delete pRoot; }}
转载地址:http://xzcoi.baihongyu.com/