LC104 二叉树的最大深度
思路1:递归遍历
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
# 2. 终止条件:
if not root: return 0
# 3. 递归调用规则
m = self.maxDepth(root.left)
n = self.maxDepth(root.right)
return max(m,n) + 1
思路2:层序遍历
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
from collections import deque
que = deque()
que.append(root)
ans = 0
while que:
size = len(que)
for _ in range(size):
node = que.popleft()
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
ans += 1
return ans
LC559 n叉树的最大深度
思路1:递归
class Solution:
def maxDepth(self, root: 'Node') -> int:
# 2. 终止条件:
if not root: return 0
# 3. 递归调用规则
max_depth = 0
for node in root.children:
max_depth = max(max_depth, self.maxDepth(node))
return max_depth + 1
思路2:层序遍历
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root: return 0
from collections import deque
que = deque()
que.append(root)
ans = 0
while que:
size = len(que)
for _ in range(size):
node = que.popleft()
for child in node.children:
que.append(child)
ans += 1
return ans
LC111 二叉树的最小深度
思路1: 递归(注意如果左右子树有一个为空时的计算方法)
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
# 2终止条件
if not root: return 0
if not root.left and root.right:
return self.minDepth(root.right) + 1
if root.left and not root.right:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
思路2:迭代(迭代到第一个左右孩子都为空的结点)
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root: return 0
from collections import deque
que = deque()
que.append(root)
ans = 0
while que:
size = len(que)
ans += 1
for _ in range(size):
node = que.popleft()
if not node.left and not node.right:
return ans
if node.left:
que.append(node.left)
if node.right:
que.append(node.right)
return ans
LC222 完全二叉树的节点个数
如果是满二叉树,返回2^n -1;如果不是,继续递归求解结点个数。
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
def isComplete(root)-> int:
# 返回满二叉树数的结点个数,如果不是,返回0
if not root: return 0
d_left = d_right = 1
p = root
while p.left:
p = p.left
d_left += 1
p = root
while p.right:
p = p.right
d_right += 1
if d_left == d_right:
return 2 ** d_left - 1
else:
return 0
# 2 终止条件
if isComplete(root):
return isComplete(root)
# 3 遍历时的操作
return self.countNodes(root.left) + self.countNodes(root.right) + 1