104. Maximum Depth of Binary Tree

电玩女神 2022-05-04 09:27 395阅读 0赞

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its depth = 3.

方法1:递归

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int maxDepth(TreeNode* root) {
  13. if(root == NULL)
  14. return 0;
  15. if(root->left == NULL && root->right == NULL)
  16. return 1;
  17. return 1 + max(maxDepth(root->left), maxDepth(root->right));
  18. }
  19. };

方法2:非递归

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. int maxDepth(TreeNode* root) {
  13. if(root == NULL)
  14. return 0;
  15. queue<TreeNode*> node;
  16. node.push(root);
  17. int count = 0;
  18. while(!node.empty())
  19. {
  20. ++count;
  21. int len = node.size();
  22. for(int i = 0; i < len;i++)
  23. {
  24. TreeNode *p = node.front();
  25. node.pop();
  26. if(p->left)
  27. node.push(p->left);
  28. if(p->right)
  29. node.push(p->right);
  30. }
  31. }
  32. return count;
  33. }
  34. };

发表评论

表情:
评论列表 (有 0 条评论,395人围观)

还没有评论,来说两句吧...

相关阅读