104.二叉树的最大深度
层次遍历-BFS思路
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:return 0
deep = 1
queue = [(root,deep)]
while queue:
node,deep = queue.pop(0)
if node.left:
queue.append((node.left,deep+1))
if node.right:
queue.append((node.right,deep+1))
return deep
递归-DFS思路
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:return 0
leftHeight = self.maxDepth(root.left)
rightHeight = self.maxDepth(root.right)
return max(leftHeight,rightHeight)+1
559.n叉树的最大深度
"""
# 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
if not root.children:return 1
return max(self.maxDepth(node)+1 for node in root.children)
"""
# 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:
queue = []
queue.append(root)
level = 0
if not root:return 0
while queue:
queueLen = len(queue)
level+=1
for i in range(queueLen):
node = queue.pop(0)
if node.children and len(node.children) > 0:
for item in node.children:
queue.append(item)
return level
111.二叉树的最小深度
错误解法 完美踩坑。。。
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:return 0
if not root.left or not root.right:return 1
leftHeight = self.minDepth(root.left)
rightHeight = self.minDepth(root.right)
return min(leftHeight,rightHeight)+1
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:return 0
if not root.left and not root.right:return 1
leftMin = self.minDepth(root.left)
rightMin = self.minDepth(root.right)
if root.left and not root.right:
return leftMin+1
if root.right and not root.left:
return rightMin+1
return min(leftMin,rightMin)+1
222.完全二叉树的节点个数
层序遍历
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:return 0
sum = 0
queue = [root]
while queue:
node = queue.pop(0)
sum+=1
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return sum
递归
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
leftdep = self.deep(root.left)
rightdep = self.deep(root.right)
if leftdep == rightdep:
return (2** leftdep -1) +self.countNodes(root.right)+1
else:
return (2**rightdep-1)+self.countNodes(root.left)+1
"""求二叉树的深度-直接用完全二叉树性质求,一直搜索其左子树"""
def deep(self,root):
deep = 0
while root:
root = root.left
deep+=1
return deep