动态规划(层次遍历)
# 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 longestZigZag(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# 动态规划字典,f表示当前结点以左节点为结尾序列的长度,g表示以右结点为结尾序列长度
f = collections.defaultdict(int)
g = collections.defaultdict(int)
# 利用层次遍历初始化队列
q = collections.deque([root])
while q:
top = q.popleft()
if top.left:
# 父节点交错序列结尾为右节点
f[top.left] = g[top] + 1
q.append(top.left)
if top.right:
# 父节点交错序列结尾为左节点
g[top.right] = f[top] + 1
q.append(top.right)
max_ = 0
# 遍历以左结点为结尾的序列长度
for value in f.values():
if value > max_:
max_ = value
# 遍历以右结点为结尾的序列长度
for value in g.values():
if value > max_:
max_ = value
return max_
动态规划(先根遍历)
# 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 longestZigZag(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# 动态规划字典,f表示当前结点以左节点为结尾序列的长度,g表示以右结点为结尾序列长度
f = collections.defaultdict(int)
g = collections.defaultdict(int)
# 先序遍历
q = [root]
while q:
top = q.pop()
if top.right:
g[top.right] = f[top] + 1
q.append(top.right)
if top.left:
f[top.left] = g[top] + 1
q.append(top.left)
# 遍历以左结点为结尾的序列长度
max_ = 0
for value in f.values():
if value > max_:
max_ = value
# 遍历以右结点为结尾的序列长度
for value in g.values():
if value > max_:
max_ = value
return max_
递归法
# 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 longestZigZag(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
self.max_ = 0
def dfs(node,is_left,length):
self.max_ = max(self.max_,length)
if is_left:
if node.left:
dfs(node.left,1,1)
if node.right:
dfs(node.right,0,length + 1)
else:
if node.left:
dfs(node.left,1,length + 1)
if node.right:
dfs(node.right,0,1)
dfs(root,False,0)
dfs(root,True,0)
return self.max_
小黑生活