leetcode-剑指 Offer 55 - I. 二叉树的深度刷题笔记(c++)

写在前面

  • 难度:简单
  • 递归 + 高度更新
    • 解题思想(化繁为简!!!
      • 问题转化巧妙
      • 树的深度为左子树的深度和右子树的深度的较大值+1.

题目详情

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

例如:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

提示:

节点总数 <= 10000

ac代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
     
public:
    int maxDepth(TreeNode* root) {
     
        if(!root) return 0;
        int lh = maxDepth(root->left);
        int rh = maxDepth(root->right);
        return lh > rh ? lh+1: rh+1;
    }
};
  • 参考文章
    • 剑指offer 面试题55 二叉树的深度

你可能感兴趣的:(leetcode,55,-,I.,二叉树的深度,树的深度)