104.二叉树的最大深度 (优先掌握递归)
层序遍历的时候加上depth++,递归类似求和
class solution {
/**
* 递归法
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> que=new LinkedList<>();
que.offer(root);
int depth=0;
while(!que.isEmpty()){
int len=que.size();
for(int i=0;i<len;i++){
TreeNode tmpNode=que.poll();
if(tmpNode.left!=null){
que.offer(tmpNode.left);
}
if(tmpNode.right!=null){
que.offer(tmpNode.right);
}
}
depth++;
}
return depth;
}
}
111.二叉树的最小深度 (优先掌握递归)
毫无区别就是一个if判断左右都是空就退出
class Solution {
public:
int minDepth(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);
if (!node->left && !node->right) {
// 当左右孩子都为空的时候,说明是最低点的一层了,退出
return depth;
}
}
}
return depth;
}
};
222.完全二叉树的节点个数(优先掌握递归)
都是递归但是第一个是不考虑是不是满二叉树的直接递归,第二个是先判断是不是满二叉树,如果是直接2的n次方-1,不是再考虑递归如上,因为总有子树是满二叉树哪怕只有一个节点
值得注意的是要加1
class Solution {
public int countNodes(TreeNode root) {
return recursiveNode(root);
}
public int recursiveNode(TreeNode root){
if(root==null){
return 0;
}
int leftNum=recursiveNode(root.left);
int rightNum=recursiveNode(root.right);
int result=leftNum+rightNum+1;
return result;
}
}
class Solution {
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
TreeNode left=root.left;
TreeNode right=root.right;
int leftdepth=0;
int rightdepth=0;
while(left!=null){
leftdepth++;
left=left.left;
}
while(right!=null){
rightdepth++;
right=right.right;
}
if(leftdepth==rightdepth){
return (2<<leftdepth)-1; //2<<1等于2的2进制10左移补0成为100 即为2的2次方
}
int leftNum=countNodes(root.left);
int rightNum=countNodes(root.right);
int sum=leftNum+rightNum+1;
return sum;
}
}