您的位置:首页 > 职场人生

《剑指Offer》面试题:二叉树的深度

2015-10-12 19:42 423 查看
题目描述:

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

思路

此题的递归思想比较简单,直接用递归将根节点的深度转换为求左右子孩子的深度的较大值+1,根节点的深度等于max(左孩子的深度,右孩子的深度)。

/*

输入:
第一行输入有n,n表示结点数,结点号从1到n。根结点为1。 n <= 10。

接下来有n行,每行有两个个整型a和b,表示第i个节点的左右孩子孩子。a为左孩子,b为右孩子。当a为-1时,没有左孩子。当b为-1时,没有右孩子。

输出:
输出一个整型,表示树的深度。

样例输入:
3
2 3
-1 -1
-1 -1
样例输出:
2
*/
/*

思路: 用递归,根节点的深度等于max(左孩子的深度,右孩子的深度)。
*/

//此题用数组存储树节点

#include<stdio.h>
#include<stdlib.h>
struct TreeNode{
int pLeftChild;
int pRightChild;
};
//递归实现
int depthInBTree(TreeNode* pRoot,int index){
if(pRoot==NULL||index==-1){//直到左右孩子时,返回0
return 0;
}
int leftDepth=depthInBTree(pRoot,pRoot[index].pLeftChild);
int rightDepth=depthInBTree(pRoot,pRoot[index].pRightChild);
return (leftDepth>rightDepth?leftDepth:rightDepth)+1;
}
int main(void){
int n;
while(scanf("%d",&n)!=EOF&&n>0&&n<=10){
TreeNode *pRoot=(TreeNode *)malloc(n*sizeof(TreeNode));
if(pRoot==NULL){
exit(EXIT_FAILURE);

}
for(int i=0;i<n;i++){
int leftIndex;
int rightIndex;
scanf("%d%d",&leftIndex,&rightIndex);
if(leftIndex!=-1){
pRoot[i].pLeftChild=leftIndex-1;
}
else{
pRoot[i].pLeftChild=-1;
}
if(rightIndex!=-1){
pRoot[i].pRightChild=rightIndex-1;
}
else{
pRoot[i].pRightChild=-1;
}
}

int depth=depthInBTree(pRoot,0);
printf("%d\n",depth);

}
return 0;
}


运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: