昨日已经做过。今日用的是新方法。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
else:
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return max(left,right) + 1
昨日已经做过。今日用的是新方法。
犯了代码随想录说的错误:
leftDepth = self.minDepth(node.left);
rightDepth = self.minDepth(node.right);
result = 1 + min(leftDepth, rightDepth);
return result;
更改后:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if root.left is None and root.right is not None:
return 1+self.minDepth(root.right)
if root.left is not None and root.right is None:
return 1+self.minDepth(root.left)
left = self.minDepth(root.left)
right = self.minDepth(root.right)
return min(left,right) + 1
这个题用前中后序遍历都可以做
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
res = []
def dfs(node):
if node == None:
return
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return len(res)
代码随想录的想法:
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
类429
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
res = []
queue = [[root]]
while queue:
one = []
for nodes in queue:
for node in nodes:
one.append(node.val)
res.append(one)
ll = []
for nodes in queue:
for node in nodes:
if node.children:
ll.append(node.children)
queue = ll
return len(res)