这道题本质上还是考查二元树的遍历
如果一棵树只有一个结点,它的深度为1。如果根结点只有左子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样如果根结点只有右子树而没有左子树,那么树的深度应该是其右子树的深度加1。如果既有右子树又有左子树呢?那该树的深度就是其左、右子树深度的较大值再加1。
上面的这个思路用递归的方法很容易实现,只需要对遍历的代码稍作修改即可
参考资料:剑指offer代码:
#include <iostream>
using namespace std;
typedef struct node{
int data;
struct node *lchild;
struct node *rchild;
}Node ,*pNode;
void createTree(pNode & root){
int temp;
scanf("%d",&temp);
if(0 != temp){
root=(pNode) malloc (sizeof(Node));
root->data = temp;
createTree(root->lchild);
createTree(root->rchild);
}else{
root=NULL;
}
}
void print(const pNode root){
pNode p = root;
if(p){
cout<< p->data<< " ";
print(p->lchild);
print(p->rchild);
}
}
//类似先序遍历,节点会重复访问,效率较低
int btDepth(const pNode root){
if(NULL == root)
return 0;
int left = btDepth(root->lchild);
int right = btDepth(root->rchild);
return left > right ? left + 1 : right + 1;
}
//类似后序遍历,效率比较高,不会重复访问节点
void btDepth(const pNode root,int &depth){
if(NULL == root){
depth=0;
return ;
}
int left ;
btDepth(root->lchild,left);
int right ;
btDepth(root->rchild,right);
depth = left > right ? left +1 : right +1;
}
int main(){
pNode root=NULL;
createTree(root);
print(root);
cout<<endl;
cout<<btDepth(root);
int depth=0;
btDepth(root,depth);
cout<<endl<<depth;
return 0;
}
二叉树测试:
运行结果: