一、二叉树或者树的问题,直接考虑广度搜索和深度搜索
二、注意判断空节点
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct BinnaryTreeNode
{
int value;
BinnaryTreeNode* left;
BinnaryTreeNode* right;
BinnaryTreeNode(int val) : value(val){}
};
int GetBinnaryTreeDepth(BinnaryTreeNode* root);
void test(char* testname,BinnaryTreeNode* root,int expect);
int GetBinnaryTreeDepth(BinnaryTreeNode* root)
{
if(root==NULL)
return 0;
int nleft = GetBinnaryTreeDepth(root->left);
int nright = GetBinnaryTreeDepth(root->right);
return nleft > nright ? (nleft+1):(nright+1);
}
void test(BinnaryTreeNode* root,int expect)
{
int result = GetBinnaryTreeDepth(root);
if(result==expect)
cout<<"Test passed..."<<endl;
else
cout<<"Test failed..."<<endl;
}
void Test1()
{
cout<<"Test1 begins.\n";
BinnaryTreeNode* t1 = new BinnaryTreeNode(1);
BinnaryTreeNode* t2 = new BinnaryTreeNode(2);
BinnaryTreeNode* t3 = new BinnaryTreeNode(3);
BinnaryTreeNode* t4 = new BinnaryTreeNode(4);
BinnaryTreeNode* t5 = new BinnaryTreeNode(5);
BinnaryTreeNode* t6 = new BinnaryTreeNode(6);
t1->left = t2;
t1->right = t3;
t3->left = NULL;
t3->right = NULL;
t2->left = t4;
t2->right = t5;
t5->left = NULL;
t5->right = NULL;
t4->left = t6;
t4->right = NULL;
t6->left = NULL;
t6->right = NULL;
test(t1,4);
}
void Test2()
{
cout<<"Test2 begins.\n";
BinnaryTreeNode* t1 = NULL;
test(t1,0);
}
int main()
{
Test1();
Test2();
return 0;
}