二叉树
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了二叉树,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2574字,纯文字阅读大概需要4分钟。
内容图文
![二叉树](/upload/InfoBanner/zyjiaocheng/1103/0ac35d140e1245f395c709772a455833.jpg)
二叉树:
二叉树是一棵特殊的树,二叉树每个节点最多有两个孩子结点,分别称为左孩子和右孩子。
实例:
节点结构:
template <class T> struct BinaryTreeNode { BinaryTreeNode(T data) :_data(data) ,_left(NULL) ,_right(NULL) {} T _data; BinaryTreeNode<T>* _left; BinaryTreeNode<T>* _right; };
二叉树成员变量;
protected: BinaryTreeNode<T>* _root;
构造函数:调用_CreateTree
Node* _CreateTree(const T* a,size_t size,size_t& index,const T& invalid)//注意index用引用 { Node* root=NULL; if((index<size)&&(a[index]!=invalid)) { root=new Node(a[index]); root->_left=_CreateTree(a,size,++index,invalid); root->_right=_CreateTree(a,size,++index,invalid); } return root; }
析构函数:调用_Destory
void _Destory(Node* root) { Node* cur=root; Node* del=cur; if(cur->_left!=NULL) { _Destory(cur->_left); } if(cur->_right!=NULL) { _Destory(cur->_right); } delete del; }
拷贝构造函数:调用_Copy
Node* _Copy(Node* root) { if(root==NULL) return NULL; Node* newroot=new Node(root->_data); Node* cur=newroot; cur->_left=_Copy(root->_left); cur->_right=_Copy(root->_right); return newroot; }
重载赋值运算符
BinaryTree& operator=(BinaryTree tree) { swap(_root,tree._root); return *this; }
前序遍历:调用_PrevOrder
void _PrevOrder(Node* root) { if(root==NULL) return; cout<<root->_data<<" "; _PrevOrder(root->_left); _PrevOrder(root->_right); }
中序遍历:调用_InOrder
void _InOrder(Node* root) { if(root==NULL) return; _InOrder(root->_left); cout<<root->_data<<" "; _InOrder(root->_right); }
后序遍历:调用_PoseOrder
void _PostOrder(Node* root) { if(root==NULL) return; _PostOrder(root->_left); _PostOrder(root->_right); cout<<root->_data<<" "; }
求深度:调用_Depth
size_t _Depth(Node* root) { Node* cur=root; size_t depth=0; if(cur==NULL) return 0; else { depth=1; size_t leftdepth=_Depth(cur->_left); size_t rightdepth=_Depth(cur->_right); if(leftdepth>=rightdepth) { return depth+leftdepth; } else { return depth+rightdepth; } } }
求size:调用_Size
size_t _Size(Node* root) { size_t count=0; if(root==NULL) return 0; else { ++count; } count+=_Size(root->_left); count+=_Size(root->_right); return count; }
求叶子节点的个数:调用_LeafSize
size_t _LeafSize(Node* root) { size_t size=0; if(root==NULL) return 0; else { if((root->_left==NULL)&&(root->_right==NULL)) { size=1; return size; } else { size_t left=_LeafSize(root->_left); size_t right=_LeafSize(root->_right); return left+right; } } }
原文:http://lovemeright.blog.51cto.com/10808587/1765914
内容总结
以上是互联网集市为您收集整理的二叉树全部内容,希望文章能够帮你解决二叉树所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。