您的位置:首页 > Web前端

leetcode-剑指offer55-I-二叉树的深度

2020-09-02 10:14 591 查看

2020-9-2

这道题是经典的求二叉树深度问题,有递归和非递归两种解法。递归的思想就是二叉树的深度等于左右子树深度的最大值加一。非递归的话就类似于广度优先搜索,将每个节点的左右子树加入队列,当一层节点遍历结束后深度加一

https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/

[code]/**
* 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)
return 0;
int max_depth = 0;
max_depth = max(maxDepth(root->left),maxDepth(root->right)) + 1;
return max_depth;
}
};

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: