状态:1刷
二刷有精力的时候 再去掌握迭代法
一、104. 二叉树的最大深度
题目:
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
思路:
递归法:
- 确定递归函数的参数和返回值: 参数就是传入树的根节点,返回就返回这棵树的深度
- 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
- 确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
代码:
class Solution {
public:
int getdepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = getdepth(node->left); // left
int rightDepth =getdepth(node->right); // right
int depth = 1 + max(leftDepth,rightDepth);
return depth;
}
int maxDepth(TreeNode* root) {
return(getdepth(root));
}
};
精简代码:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
二、111.二叉树的最小深度
题目: 给定一个二叉树,找出其最小深度。
思路:
使用后序遍历,从下往上递归
代码:
class Solution {
public:
int getDepth(TreeNode* root) {
if (root == NULL) return 0;
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
if (root->left == NULL && root->right !=NULL) {
return rightDepth + 1;
}
if (root->left != NULL && root->right == NULL) {
return leftDepth + 1;
}
int result = 1 + min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
三、 222.完全二叉树的节点个数
题目:
给出一个完全二叉树,求出该树的节点个数。
思路:
- 确定递归函数的参数和返回值:int
- 确定终止条件:如果为空节点的话,就返回0
- 确定单层递归的逻辑:先求它的左子树的节点数量,再求右子树的节点数量,最后取总和再加一 (加1是因为算上当前中间节点)就是目前节点为根节点的节点数量。
代码:
普通二叉树:
/**
// 版本二 精简版
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == NULL) return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
*/
class Solution {
public:
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;
}
int countNodes(TreeNode* root) {
return getNodesNum(root);
}
};
总结
二刷有精力的时候 再去掌握迭代法