1.二叉树的最大深度
104.二叉树的最大深度
思路:
1.深度:二叉树里任意一个结点到根结点的距离;
高度:二叉树里任意一个结点到叶子结点的距离。
2.求深度:从上到下进行计数,用后序遍历(左右中);
求高度:从下到上进行计数,用前序遍历(中左右)。
3.求二叉树的最大深度,因为二叉树的最大深度等于二叉树的最大高度,所以可以用求高度的方法进行求解(后序遍历)。利用前序遍历才是求深度的真正逻辑,但是利用前序遍历的话,代码较为复杂,会涉及到回溯。
class Solution {
public:
int maxDepth(TreeNode* root) {
//递归三部曲
if(root == NULL) return 0;
//后序(左右中)
int leftDepth = maxDepth(root -> left);
int rightDepth = maxDepth(root -> right);
int result = 1 + max(leftDepth , rightDepth);
return result;
}
};
1.该题也可以用迭代法,利用层序遍历,属于层序遍历的模板题。
2.二叉树的最小深度
111.二叉树的最小深度
思路:
1.叶子结点:左右孩子均为空。
2.本题采用后序遍历,是求高度的逻辑。和求最大深度类似。
3.求最小深度时,是到叶子结点的距离。需要考虑根结点的左孩子为空,右孩子不为空;和,根结点的左孩子不为空,右孩子为空的情况。
class Solution {
public:
int getDepth(TreeNode* node){
if(node == NULL) return 0;
//后序
int leftDepth = getDepth(node -> left);
int rightDepth = getDepth(node -> right);
if(node -> left == NULL && node -> right != NULL){
int result = 1 + rightDepth;
return result;
}
if(node -> left != NULL && node -> right == NULL){
int result = 1 + leftDepth;
return result;
}
return 1 + min(leftDepth,rightDepth);
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
1.本题也可以用前序遍历和层序遍历,前序遍历涉及到回溯,层序遍历是迭代法。
3.完全二叉树的结点个数
222.完全二叉树的节点个数
思路:
1.普通二叉树的逻辑。采用后序遍历。
class Solution {
public:
//普通二叉树
int getNodeNum(TreeNode* node){
if(node == NULL) return 0;
//后序
int leftnum = getNodeNum(node -> left);
int rightnum = getNodeNum(node -> right);
int num = 1 + leftnum + rightnum;
return num;
}
int countNodes(TreeNode* root) {
return getNodeNum(root);
}
};
class Solution {
public:
int getNodeNum(TreeNode* node){
if(node == NULL) return 0;
//前序
int count = 1;
int leftnum = getNodeNum(node -> left);
int rightnum = getNodeNum(node -> right);
count += leftnum + rightnum;
return count;
}
int countNodes(TreeNode* root) {
return getNodeNum(root);
}
};
2.利用完全二叉树的特性。
完全二叉树:1.满二叉树;2.除了最后一层外,其他层都满,且最后一层的叶子结点是从左到右依次填满。
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == NULL) return 0;
//完全二叉树特性
TreeNode* left = root -> left;
TreeNode* right = root -> right;
int leftdepth = 0;
int rightdepth = 0;
while(left){
left = left -> left;
leftdepth++;
}
while(right){
right = right -> right;
rightdepth++;
}
//判断是否为满二叉树
if(leftdepth == rightdepth) return (2 << leftdepth) - 1;
//后序
int leftnum = countNodes(root -> left);
int rightnum = countNodes(root -> right);
return leftnum + rightnum +1;
}
};