今天继续学习二叉树
1. 二叉树的最大深度
题例:二叉树的最大深度
求左子树深度,和右子树深度,再比较最大值。也可以使用迭代法的层序遍历,最后一层即是最大深度。
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
2. 二叉树的最小深度
题例:二叉树的最小深度
这个和上题原理类似,注意叶子节点为空才是最小深度。
判例需要注意,左节点为空右节点不为空即返回到右节点递归,反之则是左节点,两节点都不为空,就取两者的min值。顺序是后序遍历。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
if(root->left==NULL&&root->right!=NULL) {
return 1+minDepth(root->right);
}
if(root->right==NULL&&root->left!=NULL){
return 1+minDepth(root->left);
}
return 1+min(minDepth(root->left),minDepth(root->right));
}
};
层序遍历的话,遍历到一个node左右节点都为空,即可返回depth
3. 二叉树节点
题目给的二叉树比较特殊,是一个完全二叉树,所以可以优化迭代的写法来降低复杂度;
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr)return 0;
TreeNode* left=root->left;
TreeNode* right=root->right;
int leftdepth=0,rightdepth=0;
while(left){
left=left->left;
leftdepth++;
}
while(right){
right=right->right;
rightdepth++;
}
if(rightdepth==leftdepth){
return (2<<leftdepth)-1;
}
return countNodes(root->left)+countNodes(root->right)+1;
}
};
左和右遍历到底部,判断是否是满二叉树,若不是则返回去遍历下一层,直到遍历完元素