leetcode系列(28)Maximum Depth of Binary Tree 求二叉树的最大深度

来源:互联网 发布:淘宝上的好评怎样删除 编辑:程序博客网 时间:2024/05/16 14:19

Maximum Depth of Binary Tree

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.

这个题目用递归非常简洁,递归的key point在于描述问题,一个二叉树的最大深度必然是左右二叉树深度最大的值加1,

同时递归的边界也是实现递归的关键地方,对于二叉树类的问题,递归非常方便。

C++代码

class Solution {public:    int maxDepth(TreeNode* root) {        if (root == nullptr) {            return 0;        }        return std::max(maxDepth(root->left), maxDepth(root->right)) + 1;    }};

Python代码

class Solution:    # @param {TreeNode} root    # @return {integer}    def maxDepth(self, root):        if not root:            return 0        left = self.maxDepth(root.left)        right = self.maxDepth(root.right)         return max(left, right) + 1


0 0
原创粉丝点击