[leetcode]面试题55 - I. 二叉树的深度

题目来源:

面试题55 - I. 二叉树的深度

算法标签: dfs,二叉树

题目描述:

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

例如:

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

    3
   / \
  9  20
    /  \
   15   7
   

返回它的最大深度 3 。

提示:

节点总数 <= 10000
注意:本题与主站 104 题相同:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

思路

递归下探两个子树当中深度最大的那一个,并加上当前这一层,如果探索到的节点为NULL则直接退出。

题目代码

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:
    int maxDepth(TreeNode* root) {
		return !root?NULL:max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};


发布了155 篇原创文章 · 获赞 18 · 访问量 3910

猜你喜欢

转载自blog.csdn.net/weixin_43910320/article/details/105152535