介绍
这篇文章给大家分享的是有关c++经典例题之如何构建先序二叉树的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。
二叉树首先要解决构建问题,才能考虑后续的遍历,这里贴出通过先序构建二叉树,同时包含四种二叉树的遍历方法(先序,中序,后序,逐层)
<强>第一,定义BinaryTreeNode类强>
# include & lt; iostream> # include & lt; string> # include & lt; queue> 使用名称空间性病; template类BinaryTreeNode { 公众: 朋友类BinaryTree ; BinaryTreeNode () { 数据=https://www.yisu.com/zixun/NULL; lChild=rChild=零; } BinaryTreeNode (T newdata) { ->数据=newdata; lChild=rChild=零; } T getData () { 返回数据; } BinaryTreeNode * getLeftNode () { 返回lChild; } BinaryTreeNode * getRightNode () { 返回rChild; } T数据; BinaryTreeNode * lChild; BinaryTreeNode * rChild; 私人: };
<强>第二,定义BinaryTree类强>
模板& lt; typename T>类BinaryTree { 公众: BinaryTreeNode*根; char * p; BinaryTree(){根=零;} BinaryTree (T数据){ 根=new BinaryTreeNode (数据); 根→lChild=零; 根→rChild=零; } ~ BinaryTree () { 删除根; }//构建二叉树并返回 BinaryTreeNode * CreateTree () { BinaryTreeNode * bt=零; char t; ,cin祝辞的在t; 如果(t==& # 39; # & # 39;) { 返回NULL; } 其他{ int num=t - & # 39; 0 & # 39;; bt=new BinaryTreeNode (num); bt→lChild=CreateTree (); bt→rChild=CreateTree (); } 返回英国电信; }//先序构建二叉树 BinaryTreeNode * PreCreateTree () { BinaryTreeNode * bt=零; 如果(这→根==NULL) { cout & lt; & lt;“请输入根节点(#代表空树):“; } 其他{ cout & lt; & lt;“请输入节点(#代表空树):“; } char t; ,cin祝辞的在t; 如果(t==& # 39; # & # 39;) { 返回NULL; } 其他{ int num=t - & # 39; 0 & # 39;; bt=new BinaryTreeNode (num); 如果(这→根==NULL) { 这→根=bt; } cout & lt; & lt;bt→数据& lt; & lt;“的左孩子“; bt→lChild=PreCreateTree (); cout & lt; & lt;bt→数据& lt; & lt;“的右边孩子“; bt→rChild=PreCreateTree (); } 返回英国电信; } 空白preOderTraversal (BinaryTreeNode * bt);//先序遍历 空白inOrderTraversal (BinaryTreeNode * bt);//中序遍历 空白postOrderTraversal (BinaryTreeNode * bt);//后序遍历 空白levelTraversal (BinaryTreeNode * bt);//逐层遍历 私人: }; 模板& lt; typename T> 空白BinaryTree * bt) { 如果(bt) { cout & lt; & lt;bt→数据; BinaryTree 空白BinaryTree * bt) { 如果(bt) { BinaryTree 空白BinaryTree * bt) { 如果(bt) { BinaryTree 空白BinaryTree * bt) { queue *比;问; que.push (bt); 而(! que.empty ()) { BinaryTreeNode * proot=que.front (); que.pop (); cout & lt; & lt;proot→数据; 如果(proot→lChild !=NULL) { que.push (proot→lChild);//左孩子入队 } 如果(proot→rChild !=NULL) { que.push (proot→rChild);//右孩子入队 } } }
<强>第三,主程序运行强>
# include“pch.h" # include & lt; iostream> # include“BinaryTree.h" int main () {//场景测试2 BinaryTreec++经典例题之如何构建先序二叉树