LeetCode 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 getdepth(TreeNode *root) {
if (root == NULL) return 0;
int leftdepth = getdepth(root->left);
int rightdepth = getdepth(root->right);
int depth = 1 + max(leftdepth, rightdepth);
return depth;
}
int maxDepth(TreeNode* root) {
return getdepth(root);
}
};
递归可能有一点抽象,不过可以用纸画一画帮助理解。
LeetCode 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 getdepth(TreeNode* root) {
if (root == NULL) return 0;
int leftdepth = getdepth(root->left);
int rightdepth = getdepth(root->right);
if (root->right == NULL && root->left != NULL) return 1 + leftdepth;
if (root->right != NULL && root->left == NULL) return 1 + rightdepth;
int result = 1 + min(leftdepth, rightdepth);
return result;
}
int minDepth(TreeNode* root) {
return getdepth (root);
}
};
其实要注意的细节就是最小深度的定义也就是
if (root->right == NULL && root->left != NULL) return 1 + leftdepth;
if (root->right != NULL && root->left == NULL) return 1 + rightdepth;
这两段的原因。
LeetCode 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 getNodenum(TreeNode* root) {
if (root == NULL) return 0;
int leftnum = getNodenum(root->left);
int rightnum = getNodenum(root->right);
int result = 1 + leftnum + rightnum;
return result;
}
int countNodes(TreeNode* root) {
return getNodenum(root);
}
};
跟着“递归三部曲”来走就不会出错。
今日学习4小时收获
今天主要学习了二叉树各种遍历方法的运用,对这种类型的题有了较清晰的思路和想法。不过进度还需要继续追赶。多多重复,百炼成钢。