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
*/