迭代法,大家可以直接过,二刷有精力的时候 再去掌握迭代法。
104.二叉树的最大深度 (优先掌握递归)
什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。
大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。
题目链接/文章讲解/视频讲解: 代码随想录
二叉树深度和高度是不同的概念,顺序是相反的,高度从叶子往根部递增,深度是从根部往叶子递增;求深度用的是前序遍历,求高度用的是后序遍历。
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
这个题因为刚好最大深度==高度。深度高度均从0开始。
Python递归:
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
result = 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
return result
# 真正的过程拆解,可以写清楚前序遍历或者后序遍历。
# 用后序遍历求高度
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
left_height = self.maxDepth(root.left) # 左
right_height = self.maxDepth(root.right) # 右
height = 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) # 中
return height
C++递归:
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root==NULL) return 0;
int result = 1 + max(maxDepth(root->left), maxDepth(root->right));
return result;
}
};
拓展:559.n叉树的最大深度
Python递归:
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root: return 0
depth = 0
for child in root.children:
depth = max(depth, self.maxDepth(child))
return depth+1
C++递归:
class Solution {
public:
int maxDepth(Node* root) {
if (root==NULL) return 0;
int depth = 0;
if (root!=NULL) {
for (int i=0; i<root->children.size(); i++) {
depth = max(depth, maxDepth(root->children[i]));
}
}
return depth+1;
}
};
111.二叉树的最小深度 (优先掌握递归)
先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。
题目链接/文章讲解/视频讲解:代码随想录
这里要注意深度是从叶子往根部访问,需要考虑的是有叶的边,如果左边没有叶子,那么考虑右边,反之亦然。仍然可以用后序遍历实现,代码较简单。
Python递归:
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
left_height = self.minDepth(root.left)
right_height = self.minDepth(root.right)
if left_height == 0:
height = 1 + right_height
elif right_height == 0:
height = 1 + left_height
else:
height = 1 + min(left_height, right_height)
return height
C++递归:
class Solution {
public:
int minDepth(TreeNode* root) {
if (root==NULL) return 0;
int left_height = minDepth(root->left);
int right_height = minDepth(root->right);
int height;
if (left_height==0) {
height = 1 + right_height;
} else if (right_height==0) {
height = 1 + left_height;
} else {
height = 1 + min(left_height, right_height);
}
return height;
}
};
222.完全二叉树的节点个数(优先掌握递归)
需要了解,普通二叉树 怎么求,完全二叉树又怎么求
题目链接/文章讲解/视频讲解:代码随想录
Python递归:
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
left_node = self.countNodes(root.left)
right_node = self.countNodes(root.right)
result = 1 + left_node + right_node
return result
C++递归:
class Solution {
public:
int countNodes(TreeNode* root) {
if (root==NULL) return 0;
int left_node = countNodes(root->left);
int right_node = countNodes(root->right);
int result = 1 + left_node + right_node;
return result;
}
};