题目链接:传送门

Description

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.

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

    3
/ \
9 20
/ \
15 7

return its depth = 3.

Solution

题意:

求一棵二叉树的最大深度

思路:

dfs

/**
 * 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:
    void dfs(TreeNode* root, int depth, int &res) {
        if (!root)  return ;
        res = max(res, depth);
        dfs(root->left, depth + 1, res);
        dfs(root->right, depth + 1, res);
    }
    int maxDepth(TreeNode* root) {
        if (!root)  return 0;
        int res = 0;
        dfs(root, 1, res);
        return res;
    }
};

相关文章:

  • 2021-08-14
  • 2021-05-19
  • 2022-12-23
  • 2022-01-02
  • 2021-06-16
猜你喜欢
  • 2021-09-07
  • 2021-05-02
  • 2021-12-10
  • 2021-07-22
  • 2021-08-07
  • 2022-12-23
  • 2021-09-23
相关资源
相似解决方案