104.二叉树的最大深度 559.n叉树的最大深度
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
思路: 二叉树的最大深度就是根节点的高度,采用后序遍历,求左右子树的高度+1就是树的深度。
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
int leftdepth = maxDepth(root->left); // 左
int rightdepth = maxDepth(root->right); // 右
int depth = 1 + max(leftdepth, rightdepth); // 中
return depth;
}
};
n叉树的最大深度,就是将二叉树遍历左右子树的部分改成遍历n个子树即可。
class Solution {
public:
int maxDepth(Node* root) {
if (root == 0) return 0;
int depth = 0;
for (int i = 0; i < root->children.size(); i++) {
depth = max (depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};
111.二叉树的最小深度
与求二叉树的最大深度类似,最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
注意: 最小深度是到叶子节点开始算,不是根节点没有左子树最小深度就为1.
class Solution {
public:
int minDepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = minDepth(node->left);
int rightDepth = minDepth(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;
}
};
222.完全二叉树的节点个数
思路: 根据完全二叉树的特点,记录他的节点个数,可以直接采用层序遍历,遍历每一层记录每一层节点数量,最后求和。
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
if (root != NULL) que.push(root);
int result = 0;
while (!que.empty()) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
result++;
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return result;
}
};