20170816_二叉树的深度

20170816_二叉树的深度


//二叉树的深度
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;

struct BiTreeNode
{
	int val;
	BiTreeNode *pLeft;
	BiTreeNode *pRight;
	BiTreeNode(int x):val(x),pLeft(nullptr),pRight(nullptr) {}
};
//创建二叉树
void CreatBiTree(BiTreeNode * &root)
{
	int ch;
	cin>>ch;
	getchar();
	if(ch == -1)
	{
		root=NULL;
	}
	else
	{
		root=new BiTreeNode(ch);
		CreatBiTree(root->pLeft);
		CreatBiTree(root->pRight);
	}
}
//前序遍历二叉树:借助栈stack
void PreOrder(BiTreeNode *root)
{
	if(root==nullptr)
		return;
	stack<BiTreeNode *> s;
	while(root != nullptr || !s.empty())
	{
		while(root != nullptr)
		{
			cout<<root->val<<" ";
			s.push(root);
			root=root->pLeft;
		}
		if(!s.empty())
		{
			root=s.top();
			s.pop();
			root=root->pRight;
		}
	}
}

//求二叉树的深度
class Solution
{
public:
	int TreeDepth(BiTreeNode *root)
	{
		if(root==nullptr)
			return 0;
		else
		{
			int left=TreeDepth(root->pLeft)+1;
			int right=TreeDepth(root->pRight)+1;
			return (left>right)?left:right;
		}
	}
};

//*****************************************
int main()
{
	BiTreeNode *root;
	cout<<"依次输入二叉树的结点数据:"<<endl;		// 1 2 4 -1 7 -1 -1 -1 3 5 -1 -1 6 -1 -1
	CreatBiTree(root);
	cout<<"二叉树建立完成."<<endl;
	cout<<"前序遍历二叉树."<<endl;
	PreOrder(root);
	cout<<endl;
	cout<<"前序遍历二叉树完成."<<endl;

	class Solution object;
	int treeDepth=object.TreeDepth(root);
	cout<<treeDepth<<endl;

	system("pause");
	return 0;
}

/*
依次输入二叉树的结点数据:
1 2 4 -1 7 -1 -1 -1 3 5 -1 -1 6 -1 -1
*/





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值