二叉树深度和宽度
二叉树最大,最小深度
# Definition for a binary tree node.
class TreeNode():
def __init__(self, val0=0, left0=None, right0=None):
self.val = val0
self.left = left0
self.right = right0
class Solution():
def maxDepth(self, root):
"""
root: TreeNode
returntype: int
"""
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) +1
# 以上:深度优先搜索,时间复杂度O(N)-每个节点递归中只被遍历一次,空间复杂度O(logN)-递归需要栈空间O(height)。
def minDepth(self, root):
if not root:
return 0
if not root.left and not root.right:
return 1
min_depth = 10**9
if root.left:
min_depth = min(self.minDepth(root.left), min_depth)
if root.right:
min_depth = min(self.minDepth(root.right), min_depth)
return min_depth + 1
# 以上:深度优先搜索,时间复杂度O(N)-每个节点递归中只被遍历一次,空间复杂度O(logN)-递归需要栈空间O(height)。
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
que = collections.deque([(root, 1)])
while que:
node, depth = que.popleft()
if not node.left and not node.right:
return depth
if node.left:
que.append((node.left, depth + 1))
if node.right:
que.append((node.right, depth + 1))
return 0
# 以上:广度优先搜索,时间复杂度O(N)-每个节点递归中只被遍历一次,空间复杂度O(N)-空间复杂度主要取决于队列的开销,队列中的元素个数不会超过树的节点数。
二叉树最大宽度
# Definition for a binary tree node.
class TreeNode():
def __init__(self, val0=0, left0=None, right0=None):
self.val = val0
self.left = left0
self.right = right0
class Solution():
def maxWidth(self, root):
# 以上:深度优先搜索,时间复杂度O(N)-每个节点递归中只被遍历一次,空间复杂度O(N)
def maxWidth(self, root: TreeNode) -> int:
res = 1
arr = [[root, 1]]
while arr:
tmp = []
for node, index in arr:
if node.left:
tmp.append([node.left, index * 2])
if node.right:
tmp.append([node.right, index * 2 + 1])
res = max(res, arr[-1][1] - arr[0][1] + 1)
arr = tmp
return res
# 以上:广度优先搜索,时间复杂度O(N)-每个节点递归中只被遍历一次,空间复杂度O(N)
前序后序遍历
# 前序遍历
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
def preorder(root: TreeNode):
if not root:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
res = list()
preorder(root)
return res
def postorderTraversal(self, root: TreeNode) -> List[int]:
def postorder(root: TreeNode):
if not root:
return
postorder(root.left)
postorder(root.right)
res.append(root.val)
res = list()
postorder(root)
return res