LT38 二叉树的深度
递归法:
# 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: TreeNode) -> int:
if not root: return 0
return max(self.maxDepth(root.left),self.maxDepth(root.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 maxDepth(self, root: TreeNode) -> int:
ans = 0
if not root: return ans
stack = [root]
while stack:
ans += 1
tmp = stack
stack = []
for node in tmp:
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
return ans
LT662 二叉树最大宽度
LT662 二叉树最大宽度
给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空,也会计算在内。
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: 4
解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。
输入:
1
/ \
3 2
/
5
输出: 2
解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)
非递归法:
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
if not root: return 0
queue = [(root,1)]
width = 0
while queue:
size = len(queue)
for i in range(size):
node, nums = queue.pop(0)
if i ==0:
bgn = nums
if i == size-1:
end = nums
width = max(width, end-bgn+1)
if node.left: queue.append((node.left, 2*nums))
if node.right:queue.append((node.right, 2*nums+1))
return width