题目:输入一棵二叉树的根节点,求该树的深度。从根节点到叶子结点一次经过的结点形成树的一条路径,最长路径的长度为树的深度。根节点的深度为1。
解体思路:
如果根节点为空,则深度为0,返回0,递归的出口
如果根节点不为空,那么深度至少为1,然后我们求他们左右子树的深度,
比较左右子树深度值,返回较大的那一个
解体思路:
如果根节点为空,则深度为0,返回0,递归的出口
如果根节点不为空,那么深度至少为1,然后我们求他们左右子树的深度,
比较左右子树深度值,返回较大的那一个
通过递归调用
以下是我的代码实现:
[/u1/yyang/study/algorithm/binarytree] (171)yyang@dcmvrh12#cat treedepth.cpp
#include <stdio.h>
#include <stdlib.h>
typedef struct BinaryTreeNode
{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
}BTN;
BTN* CreateBTNode(int value)
{
BTN* btnode = new BinaryTreeNode();
if(btnode)
{
btnode->value = value;
btnode->left = NULL;
btnode->right = NULL;
}
return btnode;
}
void CreateBTree(BTN* root, BTN* left, BTN* right)
{
if(root)
{
root->left = left;
root->right =right;
}
}
int TreeDepth(BTN* root)
{
if(root == NULL)
return 0;
int left = 1;
int right =1;
if(root->left) left += TreeDepth(root->left);
if(root->right) right += TreeDepth(root->right);
return left > right ? left : right;
}
void DeleteNode(BTN* root)
{
if(root == NULL)
return ;
if(root->left) DeleteNode(root->left);
if(root->right) DeleteNode(root->right);
delete root;
root = NULL;
}
int main ()
{
// 1
// / \
// 2 3
// /\ \
// 4 5 6
// /
// 7
//create BTN*node
BTN* btnode1 = CreateBTNode(1);
BTN* btnode2 = CreateBTNode(2);
BTN* btnode3 = CreateBTNode(3);
BTN* btnode4 = CreateBTNode(4);
BTN* btnode5 = CreateBTNode(5);
BTN* btnode6 = CreateBTNode(6);
BTN* btnode7 = CreateBTNode(7);
CreateBTree(btnode1,btnode2,btnode3);
CreateBTree(btnode2,btnode4,btnode5);
CreateBTree(btnode3,NULL,btnode6);
CreateBTree(btnode5,btnode7,NULL);
int depth = TreeDepth(btnode1);
printf("The Binary Tree Depth is %d\n",depth);
//free the node
DeleteNode(btnode1);
}
运行结果:
[/u1/yyang/study/algorithm/binarytree] (169)yyang@dcmvrh12#./btdepth
The Binary Tree Depth is 4
网上很多的算法是没有去做一些申请成功的判断和最后的释放节点。希望多多指教。