104.二叉树的最大深度 (优先掌握递归)
二叉树的高度:该结点到叶子结点的差值+1,即叶子节点的高度为1
二叉树的深度:该节点到根节点的差值+1,根节点高度为1.
//递归,最大高度=最大深度,所以通过后序遍历求最大高度
class Solution {
public:
int findMaxDepth(TreeNode* node){
if (node==nullptr) return 0;
int leftDepth = findMaxDepth(node->left);
int rightDepth = findMaxDepth(node->right);
return max(leftDepth, rightDepth) + 1;
}
int maxDepth(TreeNode* root) {
return findMaxDepth(root);
}
};
// 迭代,层序遍历,每次更新当前层的节点数时,记录深度。
class solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
int depth = 0;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
int size = que.size();
depth++; // 记录深度
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return depth;
}
};
111.二叉树的最小深度
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
class Solution {
public:
int GetDepth(TreeNode* node){
if (node==nullptr) return 0;
int leftDepth = GetDepth(node->left);
int rightDepth = GetDepth(node->right);
if (node->left==nullptr && node->right!=nullptr) return 1+rightDepth;
if (node->right==nullptr && node->left!=nullptr) return 1+leftDepth;
int result = 1+ min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return GetDepth(root);
}
};
有点绕,对于左子树和右子树皆有的节点而言会返回result = 1+ min(leftDepth, rightDepth);而对于左子树右子树仅存在一个的节点会继续沿着存在的那条树枝查找。
if (node->leftnullptr && node->right!=nullptr) return 1+rightDepth;
if (node->rightnullptr && node->left!=nullptr) return 1+leftDepth;
保证了根节点为单枝的时候不会返回0。因为只有具有双枝的节点有资格返回result。
222.完全二叉树的节点个数
class Solution {
public:
int GetNodesNum(TreeNode* node){
if(node==nullptr) return 0;
int leftNum = GetNodesNum(node->left);
int rightNum = GetNodesNum(node->right);
int treeNum = leftNum+rightNum+1; //对这句话的理解是,如果当前节点的左右孩子都为null,说明这是叶子结点,返回1
return treeNum;
}
int countNodes(TreeNode* root) {
return GetNodesNum(root);
}
};
// 非递归写法
class Solution {
public:
int countNodes(TreeNode* root) {
if (root==nullptr) return 0;
queue<TreeNode*> que;
que.push(root);
int counter=0;
while (!que.empty()){
int size = que.size();
counter+=size;//加每一层的节点个数
while (size--){
TreeNode* node = que.front();
que.pop();
if (node->left!=nullptr) que.push(node->left);
if (node->right!=nullptr) que.push(node->right);
}
}
return counter;
}
};
//用完全二叉树是由若干满二叉树组合而成的的思想
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 (leftDepth == rightDepth){
return (2<<leftDepth)-1; //(2^leftDepth)-1,求每一个小满二叉树的个数
}
int leftTreeNum = countNodes(root->left);
int rightTreeNum = countNodes(root->right);
int result = leftTreeNum + rightTreeNum + 1;
return result;
}
};