2014
02-13

# 剑指offer(14)-二叉树的深度[数据结构]

3
2 3
-1 -1
-1 -1

2

#include<stdio.h>

int a[20][2];

int TreeDepth(int i,int n)
{

if (i==-1)
{
return 0;
}

int ldep =0;
if (a[i-1][0]!=-1)
{
ldep = TreeDepth(a[i-1][0],n);
}
int rdep =0;
if (a[i-1][1]!=-1)
{
rdep =  TreeDepth(a[i-1][1],n);
}
return ldep>rdep?ldep+1:rdep+1;
}

int main()
{

int n;
while(~scanf("%d",&n))
{
int i;
for (i=0;i<n;i++)
{
scanf("%d%d",&a[i][0],&a[i][1]);
}
int depth = TreeDepth(1,n);
printf("%d\n",depth);
}
return 0;
}

/**************************************************************
Problem: 1350
User: 从此醉
Language: C++
Result: Accepted
Time:0 ms
Memory:1020 kb
****************************************************************/

1. simple, however efficient. A lot of instances it is difficult to get that a??perfect balancea?? among usability and appearance. I must say that youa??ve done a exceptional task with this. Also, the blog masses quite fast for me on Web explore.

2. 我还有个问题想请教一下，就是感觉对于新手来说，递归理解起来有些困难，不知有没有什么好的方法或者什么好的建议？