求二叉树深度的递归与非递归算法实现

  1. /** 二叉树深度的递归算法 */ 
  2. int depth(BTree root)
  3. {
  4. int ldepth,rdepth;
  5. if(!root)     return 0;
  6. else{
  7. ldepth = depth(root->lchild);
  8. rdepth = depth(root->rchild);
  9. return ldepth>rdepth?ldepth+1;rdepth+1;
  10. }
  11. /** 二叉树深度的非递归算法(在中根遍历算法的基础上修改的来)
  12. http://blog.csdn.net/panqiaomu/archive/2007/05/17/1612556.aspx */
  13. int depth2(BTree root){
  14. int top = 0;
  15. int depth = 0,temp = 0;//temp 保存当前单分支的最大值
  16. BTree p = root;
  17. BTree nodePointer[MAX_TREE_DEGREE];
  18. while(p || top > 0){
  19. if(p){
  20. nodePointer[top] = p;
  21. ++ top;
  22. ++ depth; //统计单分支的深度 
  23. p = p->lchild;
  24. }else{
  25. -- top;
  26. p = nodePointer[top];
  27. p = p->rchild;
  28. if(p == NULL){ //单分支结束
  29. if(depth > temp )
  30. temp = depth;
  31. -- depth;
  32. }
  33. }//else
  34. }//while
  35. return temp;
  36. }
posted @ 2011-06-01 09:16  itbird  Views(13623)  Comments(0)    收藏  举报