104. 二叉树的最大深度通过后序遍历,用递归法求得每个节点左树右树的深度。为什么采用后序遍历,因为最后访问根节点会将迭代的值返回给根节点。最后取左右最大的深度+1(加根节点本身)即可。
思想和上一题差不多,但是有一个坑要注意,深度是根节点到叶子的距离,因此如果存在莫个结点的左树或者右树为空的情况,不能只加到为空的位置,而是:若左树为空就1+右树最小深度,右树同理,最后再取二者最小值加1
/**
* 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 getDeepth(TreeNode* root){
if(root==NULL) return 0;
int leftDepth = getDeepth(root->left);
int rightDepth = getDeepth(root->right);
if(root->left==NULL&&root->right!=NULL){
return 1+rightDepth;
}
else if(root->left!=NULL&&root->right==NULL){
return 1+leftDepth;
}
else {
return 1+min(leftDepth,rightDepth);
}
}
int minDepth(TreeNode* root) {
return getDeepth(root);
}
};
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 getCount(TreeNode* root){
if(root==NULL) return 0;
int leftNums = getCount(root->left);
int rightNums = getCount(root->right);
int nums = 1+leftNums+rightNums;
return nums;
}
int countNodes(TreeNode* root) {
return getCount(root);
}
};