代码随想录算法训练营第十六天 | 104. 二叉树的最大深度、559. N 叉树的最大深度、111. 二叉树的最小深度、222. 完全二叉树的节点个数
104. 二叉树的最大深度
题目链接:104. 二叉树的最大深度
-
根节点的高度就是二叉树的最大深度
-
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数
-
提供一种遍历做法,类似于回溯
class Solution { int depth; int res; public: int maxDepth(TreeNode* root) { // 遍历做法 depth = 0; res = 0; traverse(root); return res; } void traverse(TreeNode* root) { if(root == nullptr) { return; } depth++; if(root->right == nullptr && root->left == nullptr) { res = max(depth, res); // return; 如果有return的话结果会加2 } traverse(root->left); traverse(root->right); depth--; } };
559. N 叉树的最大深度
题目链接:559. N 叉树的最大深度
-
两种做法
class Solution { public: // 分解做法 int maxDepth(Node* root) { if(root == nullptr) { return 0; } int subTreeMaxDepth = 0; for(Node* child :root->children) { subTreeMaxDepth = max(maxDepth(child), subTreeMaxDepth); } return 1 + subTreeMaxDepth; } }; -
class Solution { public: int res = 0; int depth = 0; // 遍历做法 int maxDepth(Node* root) { traverse(root); return res; } void traverse(Node* root) { if(root == nullptr) { return ; } depth++; res = max(res, depth); for(Node* child: root->children) { traverse(child); } depth--; } };
111. 二叉树的最小深度
题目链接:111. 二叉树的最小深度
- 前序求深度,后序求高度
-
class Solution { public int minDepth(TreeNode root) { if(root == null){ return 0; } int leftHeight = minDepth(root.left); int rightHeight = minDepth(root.right); // 说明不是叶子节点 if(root.left != null && root.right == null){ return leftHeight + 1; } // 说明不是叶子节点 else if(root.left == null && root.right != null){ return rightHeight + 1; } else{ return Math.min(leftHeight, rightHeight) + 1; } } }
222. 完全二叉树的节点个数
题目链接:222. 完全二叉树的节点个数
- 通过快速计算满二叉树的节点数量减少工作量
- 通过左边长和右边长判断是否为满二叉树,节点数为2^n - 1
- 时间复杂度O(logn * logn)