本文最后更新于:2021年7月22日 晚上
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
返回它的最大深度 3 。
Solution
同类型题 [559 N 叉树的最大深度]
- 递归法,后序遍历
- 根节点的高度就是二叉树的最大深度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public: int maxDepth(TreeNode* root) { int depth = 0; if(root==nullptr) return 0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return depth = max(leftDepth,rightDepth)+1; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: int maxDepth(TreeNode* root) { if (root == nullptr) return 0; queue<TreeNode *> q; int depth = 0; q.push(root); while (!q.empty()) { int n = q.size(); depth++; for (int i = 0; i < n; ++i) { TreeNode *node = q.front(); q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } return depth; } };
|
- 回溯法,前序遍历。参考 代码随想录
- 使用前序(中左右)的遍历顺序,这才是真正求深度的逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: int result; void getDepth(TreeNode* node, int depth) { result = depth > result ? depth : result;
if (node->left == NULL && node->right == NULL) return ;
if (node->left) { depth++; getDepth(node->left, depth); depth--; } if (node->right) { depth++; getDepth(node->right, depth); depth--; } return ; } int maxDepth(TreeNode* root) { result = 0; if (root == 0) return result; getDepth(root, 1); return result; } };
|