代码随想录【Day 16】 | 二叉树 104.二叉树的最大深度 (优先掌握递归) 、 111.二叉树的最小深度 (优先掌握递归)、222.完全二叉树的节点个数(优先掌握递归)
104.二叉树的最大深度
题目链接:104.二叉树的最大深度
解题思路重点:
- 没啥说的
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if ( !root ) return 0;
int leftDepth = maxDepth( root->left );
int rightDepth = maxDepth( root->right );
int ret = 1 + max( leftDepth, rightDepth);
return ret;
}
};
111.二叉树的最小深度
题目链接:111.二叉树的最小深度
解题思路重点:
- 没啥说的
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if ( !root ) return 0;
int leftDep = minDepth( root->left );
int rightDep = minDepth( root->right );
if ( !root->left && root->right )
return ( 1 + rightDep );
if ( !root->right && root->left )
return ( 1 + leftDep );
return (1 + min( leftDep, rightDep));
}
};
222.完全二叉树的节点个数(优先掌握递归)
代码实现:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if ( !root ) return 0;
int leftNum = countNodes( root->left );
int rightNum = countNodes( root->right );
return ( 1 + leftNum + rightNum);
}
};