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 2 3 4 5 6 7 8 9 10 |
class Solution { public: int maxDepth(TreeNode* root) { if(!root) return 0; int lval = maxDepth(root->left) + 1; int rval = maxDepth(root->right) + 1; return (lval > rval)? lval : rval; } }; |
有关二叉树的相关总结,请转见:二叉树学习总结