leetcode104 二叉树的最大深度
思路
后续遍历,使用递归。先遍历他的左孩子的高度,再遍历右孩子的高度。返回最后孩子高度的最大值+1
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root ==NULL){
return 0;
}
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
};
Leetcode 111 二叉树最小深度
思路
同上,不过要注意,最小深度是指根节点到最近叶子节点的距离。所以要排除左分支或者右分支为空的情况。
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) {
return 1 + rightDepth;
}
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) {
return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
LeetCode 222 完全二叉树节点个数
思路
可以利用完全二叉树的特性,当前层一共的节点个数=[2^(深度)]-1个。所以可以首先判断是否是一个满二叉树,如果是,可以按照这个公式计算。叶子节点也算。
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; // 这里初始为0是有目的的,为了下面求指数方便
while (left) { // 求左子树深度
left = left->left;
leftDepth++;
}
while (right) { // 求右子树深度
right = right->right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
}
};