码迷,mamicode.com
首页 > 其他好文 > 详细

递归二叉树建立和遍历及深度计算

时间:2015-06-10 09:04:51      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

上篇咱们说到二叉树的一种建立方法及三种遍历方法的递归非递归算法。这篇换了一种新的建立方法,用先根遍历递归的思路建立二叉树,用递归的方法计算深度,用中根递归和非递归方法遍历整个二叉树。

BinaryTree.h

//二叉树的建立和遍历
#ifndef BINARYTREE_H_
#define BINARYTREE_H_
#include <iostream>
typedef int T;
struct Node
{
	T data;
	Node *lch;
	Node *rch;
};
class BinaryTree
{
private:
	Node *root;
	Node *create_bt();
	void inorder(Node *p);
	int predepth(Node *t);
	void destroy(Node *p);
	int max(int x, int y);
public:
	BinaryTree()
	{
		root=NULL;
	}
	~BinaryTree()
	{
		destroy(root);
	}
	void create();
	void inorder()
	{
		inorder(root);
	}
	void inorderz();//中根非递归遍历
	int predepth(){return predepth(root);}//求二叉树的深度递归函数
};

#endif
BinaryTree.cpp

#include "BinaryTree.h"
#include <iostream>
#include <stack>

using namespace std;

void BinaryTree::create()
{
	cout<<"请按照二叉树先根次序,且将空孩子置为0,组织数据"<<endl;
	cout<<"每次输入结点的数据,假设是一棵3个结点的满二叉树。"<<endl;
	cout<<"那么输入应是:11 22 0 0 33 0 0"<<endl;
	root=create_bt();
}
Node *BinaryTree::create_bt()
{
	Node *t;
	int e;
	cout<<"输入结点的值:";
	cin>>e;
	if(e==0)
		t=NULL;
	else
	{
		t=new Node;
		t->data=e;
		t->lch=create_bt();
		t->rch=create_bt();
	}
	return t;
}
void BinaryTree::inorderz()//中根非递归遍历
{
	Node *p=root;  
    Node *q;  
    stack<Node *> S;  
    do  
    {  
        while(p!=NULL)  
        {  
            S.push(p);  
            p=p->lch;  
        }  
        p=S.top();  
        S.pop();  
        cout<<p->data<<" ";  
        p=p->rch;      
    }while(!(S.empty() && p==NULL));  
}
void BinaryTree::inorder(Node *p)
{
	if(p!=NULL)
	{
		inorder(p->lch);
		cout<<p->data<<" ";
		inorder(p->rch);
	}
}
int BinaryTree::predepth(Node *t)
{
	if(t!=NULL)
	{
		return 1+max(predepth(t->lch),predepth(t->rch));
	}
	else
		return 0;
}
int BinaryTree::max(int x, int y)
{
	return (x>=y?x:y);
}
//用递归法删除二叉树的所有结点
void BinaryTree::destroy(Node *p)
{
	if(p!=NULL)
	{
		destroy(p->lch);
		destroy(p->rch);
	}
	delete p;
}
main.cpp

#include <iostream>
#include "BinaryTree.h"

using namespace std;

int main()
{
	BinaryTree BT;
	BT.create();
	cout<<"中根递归遍历:"<<endl;
	BT.inorder();
	cout<<"中根非递归遍历:"<<endl;
	BT.inorderz();
	cout<<endl<<"二叉树的深度为:"<<BT.predepth()<<endl;
	system("pause");
	return 0;
}
结果为:

技术分享






递归二叉树建立和遍历及深度计算

标签:

原文地址:http://blog.csdn.net/jiang111_111shan/article/details/46431827

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!