Open fockspaces opened 11 months ago
GPT improve:
# 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:
self.ans = 0
def DFS(root):
if not root:
return 0, 0
left_zig, _ = DFS(root.left)
_, right_zig = DFS(root.right)
self.ans = max(self.ans, left_zig, right_zig)
return right_zig + 1, left_zig + 1
DFS(root)
return self.ans
此題不能對每個 node 都 DFS 一遍,會 TTL 因此想到另一個方法,和求 tree height 有點像,在 DFS 過程更新 ans,並將必要資訊回傳 DFS 會將左右拐點的最大長度回傳,左子能接其右拐,反之