104. 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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
思路
递归思想的编程练习。非递归方法就不实现了。
/**
* 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==NULL) return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return max(l,r)+1;
}
};

本文探讨了如何使用递归方法找到二叉树的最大深度。通过遍历树的每个节点,递归地计算左右子树的深度,并返回较大者加一,最终得到整棵树的最大深度。

290

被折叠的 条评论
为什么被折叠?



