二叉树的C++实现
2015-08-13 18:16
405 查看
1.二叉树构建的几种方法:
<1>基于数组的顺序存储结构的实现
<1>基于数组的顺序存储结构的实现
#include<iostream> using namespace std; #define N 10 class treenode { friend treenode* create(int val); friend void LstOrder(treenode*& node); public: treenode() :rightchild(nullptr), leftchild(nullptr){} ~treenode(){} treenode*& getright() { return rightchild; } treenode*& getleft() { return leftchild; } private: int value; treenode* rightchild; treenode* leftchild; }; treenode* create(int val) { treenode* newnode = new treenode; newnode->value = val; newnode->leftchild = nullptr; newnode->rightchild = nullptr; return newnode; } int main() { treenode* ptr = { nullptr }; //建立一个存储节点地址的数组 for (int i = 0; i < N; ++i) //连续产生n个节点 ptr[i]=create(i+1); //将n个节点按照层次顺序链接起来 for (int i = 0; i < N / 2; ++i) { if (2 * i+1 < N) ptr[i]->getleft() = ptr[2*i+1]; if (2 * i+2 < N) ptr[i]->getright() = ptr[2*i+2]; } system("pause"); return 0; }<2> 基于链表结构的构建
template<class T> void tree<T>::createtree(treenode<T>*& node) { char temp; std::cout << "请输入:" << std::endl; std::cin >> temp; if (temp == '#') node = nullptr; else { node = new treenode < T > ; node->value = temp; createtree(node->leftchild); createtree(node->rightchild); } }2.二叉树的深度
template<class T> int tree<T>::depth(treenode<T>*& node) { if (node == nullptr) return 0; else { return 1 + max(depth(node->rightchild), depth(node->leftchild)); } } int max(int s1, int s2) { if (s1 > s2) return s1; else return s2; }
相关文章推荐
- VS中的路径宏 vc++中OutDir、ProjectDir、SolutionDir各种路径
- 【c++】字符串中找出最长的连续数字字符串
- c语言为什么要声明
- Minimum Transport Cost
- 黑马程序员———C语言———【函数指针、指针函数、野指针、内存管理、const关键字】
- C++ primer 【笔记】关联容器 set
- C/C++:内存字节对齐详解
- VS2010 C++ 学习笔记(二) 内存管理 new delete
- 【一】C++基于C的一些改变
- 位运算
- C++ 共享数据(一)静态
- C++程序中调用WebService的实现
- [LeetCode] Best Time to Buy and Sell Stock II
- c++ 宏的使用
- OpenWRT开发之——对C++的支持(解决库依赖问题)
- 黑马程序员—-C语言入门十重奏之四相恋
- c++ 预处理的应用
- [LeetCode] Best Time to Buy and Sell Stock
- 链式队列的C++实现
- const限定符和constexpr初探