欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢
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.
树的深度是从根节点开始(其深度为1)自顶向下逐层累加的,而高度是从叶节点开始(其高度为1)自底向上逐层累加的。
class Solution { private: int depth = 0; void maxDepthUtil(TreeNode *root , int d) { if(root == NULL) return; if(d > depth) depth = d; maxDepthUtil( root->left, d+1); maxDepthUtil( root->right, d+1); } public: int maxDepth(TreeNode *root) { maxDepthUtil( root,1 ); return depth; } };
//另一种写法 class Solution { public: int maxDepth(TreeNode *root) { if(root == NULL) return 0; return max( maxDepth(root->left),maxDepth(root->right) )+1; } };
时间: 2024-10-07 04:34:17