52.二元树的深度(树)。
题目:输入一棵二元树的根结点,求该树的深度。
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
例如:输入二元树:
10
/ /
6 14
/ / /
4 12 16
输出该树的深度3。
二元树的结点定义如下:
struct SBinaryTreeNode // a node of the binary tree
{
int m_nValue; // value of node
SBinaryTreeNode *m_pLeft; // left child of node
SBinaryTreeNode *m_pRight; // right child of node
};
分析:这道题本质上还是考查二元树的遍历。
思路:就像上面说的一样,这道题目其实测试的还是二叉树遍历的操作。最正常的思路就是先序遍历整个树,然后每到一个叶子节点,就记录下当时的深度,并于最大深度进行比较,如果比最大的大,就更新最大记录,这样就能找到树的最大深度。
另外的思路就是采用的递归的方法,要找到一个树的深度,如果根是空的,深度就是0,如果非空,深度就是左子树和右子树中深度比较大的那个加1。这样递归的解决问题。
贴上代码:
//52.二元树的深度(树)。
//题目:输入一棵二元树的根结点,求该树的深度。
//从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
//例如:输入二元树:
// 10
// / /
// 6 14
// / / /
// 4 12 16
//输出该树的深度3。
//二元树的结点定义如下:
//struct SBinaryTreeNode // a node of the binary tree
//{
// int m_nValue; // value of node
// SBinaryTreeNode *m_pLeft; // left child of node
// SBinaryTreeNode *m_pRight; // right child of node
//};
//分析:这道题本质上还是考查二元树的遍历。
#include <iostream>
using namespace std;
struct TreeNode
{
int value;
TreeNode *pLeft;
TreeNode *pRight;
};
void addTreeNode(TreeNode *&pRoot,int *index,int &iCurrent){
if(-1 != index[iCurrent]){
TreeNode *pCurrent = new TreeNode;
pCurrent->value = index[iCurrent++];
pCurrent->pLeft = NULL;
pCurrent->pRight = NULL;
pRoot = pCurrent;
addTreeNode(pRoot->pLeft,index,iCurrent);
addTreeNode(pRoot->pRight,index,iCurrent);
}else{
++iCurrent;
}
}
void createTree(TreeNode *&pRoot,int *index){
int iCurrent = 0;
addTreeNode(pRoot,index,iCurrent);
}
void inOrder(TreeNode *pRoot){
if(NULL != pRoot){
inOrder(pRoot->pLeft);
cout << pRoot->value << " ";
inOrder(pRoot->pRight);
}
}
int treeDepth(TreeNode *pRoot){
if(NULL == pRoot){
return 0;
}else{
int leftDepth = treeDepth(pRoot->pLeft);
int rightDepth = treeDepth(pRoot->pRight);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
}
int main(){
int index[] = {10,6,4,-1,-1,-1,14,12,-1,-1,16,-1,-1};//测试数据
TreeNode *pRoot = NULL;
createTree(pRoot,index);//创建树
//inOrder(pRoot);
int ret = treeDepth(pRoot);
cout << "the depth of the tree is :" << ret << endl;
system("pause");
return 1;
}