题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最大深度为3
.
使用递归的思想,递归函数返回当前节点左右子节点的深度大的那一个。
实现代码:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef char ElemType;
typedef struct BinaryTreeNode{
char value;
struct BinaryTreeNode *lchild,*rchild;
}BinaryTreeNode,*BinaryTree;
BinaryTreeNode * CreatBiTree() {
BinaryTreeNode * node;
char data;
cin>>data;
if (data == '#') {
node = NULL;
} else {
node = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode));//new BinaryTreeNode;
node->value = data;
node->lchild = CreatBiTree();
node->rchild = CreatBiTree();
}
return node;
}
int returnMaxDepth(BinaryTreeNode *node){
if (node == NULL) {
return 0;
}
int leftDepth = returnMaxDepth(node->lchild);
int rightDepth = returnMaxDepth(node->rchild);
return leftDepth > rightDepth?leftDepth+1:rightDepth+1;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
BinaryTreeNode * rootNode = CreatBiTree();
int maxDepth = returnMaxDepth(rootNode);
return 0;
}