LeetCode 104. Maximum Depth of Binary Tree

红太狼 2022-07-27 13:39 260阅读 0赞

废话不多说,先看题目:

Given a binary tree, find its maximum depth.

题目意思:就是要求得到二叉树的深度或者高度

学过数据结构对这个肯定不会陌生,典型的递归:

  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. else
  16. {
  17. int l=maxDepth(root->left);
  18. int r=maxDepth(root->right);
  19. return r>l?r+1:l+1;
  20. }
  21. }
  22. };

发表评论

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

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

相关阅读