欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Maximum Depth of Binary Tree

发布时间:2025/4/16 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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.

Subscribe to see which companies asked this question

给定一个二叉树,找出其最大深度。 
二叉树的深度为根节点到最远叶子节点的距离。

如果二叉树为空,则深度为0 
如果不为空,分别求左子树的深度和右子树的深度,去最大的再加1,因为根节点深度是1,要加进去。

/*** 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 (NULL == root)return 0;int l = maxDepth(root->left);int r = maxDepth(root->right);return l > r ? l + 1:r+1;} };/*** 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 height(TreeNode* root) { if(root==NULL) return 0; else{ int l=height(root->left); int r=height(root->right); return 1+((l>r)?l:r); } } int maxDepth(TreeNode* root) {if (NULL == root)return 0;int l = height(root->left);int r = height(root->right);return l > r ? l + 1:r+1;} };


总结

以上是生活随笔为你收集整理的Maximum Depth of Binary Tree的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。