二元树的深度(树)

来源:互联网 发布:linux 防止暴力破解 编辑:程序博客网 时间:2024/06/10 15:29
 二元树的深度(树)
题目:输入一棵二元树的根结点,求该树的深度。
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
例如:输入二元树:
                                            10
                                          /     /
                                        6        14
                                      /         /   /
                                    4         12     16
输出该树的深度3。
二元树的结点定义如下:
struct SBinaryTreeNode // a node of the binary tree
{
      int               m_nValue; // value of node
      SBinaryTreeNode  *m_pLeft;  // left child of node
      SBinaryTreeNode  *m_pRight; // right child of node
};

分析:这道题本质上还是考查二元树的遍历。


[cpp] view plaincopyprint?
  1. //coder:LEE 20120330  
  2. #include<iostream>  
  3. #include<CASSERT>  
  4. using namespace std;  
  5. struct SBinaryTreeNode     
  6. {  
  7. int m_nValue;  
  8. SBinaryTreeNode * m_pLeft;  
  9. SBinaryTreeNode  * m_pRight;  
  10. };  
  11. void AddNode(SBinaryTreeNode  *& root,int n)  
  12. {  
  13. if (!root)  
  14. {  
  15. root=(SBinaryTreeNode  *)malloc(sizeof(SBinaryTreeNode  ));  
  16. root->m_nValue=n;  
  17. root->m_pLeft=NULL;  
  18. root->m_pRight=NULL;  
  19. return;  
  20. }  
  21. if(n<root->m_nValue)  
  22. AddNode(root->m_pLeft,n);  
  23. else  
  24. AddNode(root->m_pRight,n);  
  25. }  
  26. void Traverse(SBinaryTreeNode  * root)  
  27. {  
  28.     if(!root)  
  29.         return;  
  30.       
  31.     Traverse((root->m_pLeft));  
  32.     cout<<root->m_nValue<<"  ";  
  33.     Traverse(root->m_pRight);  
  34.       
  35. }  
  36. int ComputeDepthOfBiTree(SBinaryTreeNode * root)  
  37. {  
  38.     if(root==NULL)  
  39.         return 0;  
  40.     int LeftDepth=ComputeDepthOfBiTree(root->m_pLeft);  
  41.     int RightDepth=ComputeDepthOfBiTree(root->m_pRight);  
  42.     return LeftDepth>RightDepth?LeftDepth+1:RightDepth+1;   
  43. }  
  44. int main()  
  45. {  
  46.     SBinaryTreeNode  * root=NULL;  
  47.     AddNode(root,8);  
  48.     AddNode(root,6);  
  49.     AddNode(root,10);  
  50.     AddNode(root,5);  
  51.     AddNode(root,7);  
  52.     AddNode(root,9);  
  53.     AddNode(root,11);  
  54.     AddNode(root,12);  
  55.     Traverse(root);  
  56.     cout<<endl;  
  57.     cout<<ComputeDepthOfBiTree(root);  
  58.     return 0;  
  59. }  

0 0