Implement recursive and non-Recursive Algorithms for Binary Tree depth

Source: Internet
Author: User
  1. /** Binary Tree depth recursion algorithm */
  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. /** Non-Recursive Algorithms for Binary Tree depth (modified based on the Root Traversal Algorithm)
  13. Http://blog.csdn.net/panqiaomu/archive/2007/05/17/1612556.aspx */
  14. Int depth1 (btree root ){
  15. Int Top = 0;
  16. Int depth = 0, temp = 0; // temp stores the maximum value of the current single branch
  17. Btree P = root;
  18. Btree nodepointer [max_tree_degree];
  19. While (p | top> 0 ){
  20. If (p ){
  21. Nodepointer [Top] = P;
  22. ++ Top;
  23. ++ Depth; // count the depth of a single branch
  24. P = p-> lchild;
  25. } Else {
  26. -- Top;
  27. P = nodepointer [Top];
  28. P = p-> rchild;
  29. If (P = NULL) {// end of a single branch
  30. If (depth> temp)
  31. Temp = depth;
  32. -- Depth;
  33. }
  34. } // Else
  35. } // While
  36. Return temp;
  37. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.