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.
解题思路
求树的高度,很简单。代码如下:
/**
* 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;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
本文介绍了一种简单的方法来寻找二叉树的最大深度。通过递归遍历左右子树并比较其深度,可以找到从根节点到最远叶子节点的最长路径上的节点数量。
278

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



