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;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
int u = 0, v = 0;
if (root == NULL){
return 0;
}
u = maxDepth(root->left);
v = maxDepth(root->right);
return (u > v ? (u+1) : (v+1));
}

本文介绍了一种使用深度优先搜索算法来确定二叉树的最大深度的方法。通过递归地访问每个节点并记录路径长度,可以找到从根节点到最远叶节点的最长路径。
1299

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



