二叉树最大深度
树的深度是从根节点到最远叶子结点的距离。
二叉树节点的深度:指从根节点到该节点的最长简单路径边的距离。中左右,在第一行就会有操作,第二三行继续递归左右结点。所以在根节点就开始记录了。
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的距离。符合后序遍历的顺序,左右中,这样可以先从根结点到最底层的左叶子结点,然后右叶子结点
求树的最大深度,即求根节点的高度。
/**
* 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 maxDepth(TreeNode* root) {
if(root==nullptr) return 0;
int lefth=maxDepth(root->left);
int righth=maxDepth(root->right);
int depth=1+max(lefth,righth);
return depth;
}
};
二叉树的最小深度
从根出发到叶子结点的最小距离,可以同样用上题后序遍历,但是不能简单的把max改成min,这样的话,如果向下到叶子结点的过程中,如果左子叶为空,右边还有树,就会被直接认为成0
需要对特殊情况进一步表示。
完全二叉树结点的个数
暴力法就是前中后序迭代,然后每次在中的位置那里加一。
class Solution {
private:
int getNodesNum(TreeNode* cur) {
if (cur == NULL) return 0;
int leftNum = getNodesNum(cur->left); // 左
int rightNum = getNodesNum(cur->right); // 右
int treeNum = leftNum + rightNum + 1; // 中
return treeNum;
}
public:
int countNodes(TreeNode* root) {
return getNodesNum(root);
}
};
或者对层序遍历有一个简单的修改
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;
}
};
但上述两种方法时间复杂度为O(n),这是一棵完全二叉树,完全可以把它拆分成满二叉树和普通二叉树,判断其子树是不是满二叉树,如果是则利用公式计算这个子树(满二叉树)的节点数量,如果不是则继续递归。
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;
}
};