LeetCode-104. Maximum Depth of Binary Tree

来源:互联网 发布:java如何记录接口日志 编辑:程序博客网 时间:2024/05/24 05:27

问题:https://leetcode.com/problems/maximum-depth-of-binary-tree/?tab=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.
分析:二叉树的最大深度,是左子树和右子树深度的最大值加1。用递归比较容易求得。
参考C++代码:

/** * 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(NULL==root) return 0;        if(NULL==root->left && NULL==root->right) return 1;        int l=maxDepth(root->left);        int r=maxDepth(root->right);        return l>=r?l+1:r+1;    }};
0 0