【题目】
每棵树最多有 50000 个节点。
每个节点的值在 [1, 100] 之间。
【代码】
【方法1】超时!!!虽然结果正确,但是时间复杂度高,结果超时,仍然提供出来,作为参考:
class Solution:
def visit(self,root,loc=0):
if not root:
return
self.path.append(loc)
self.visit(root.left,-1)
self.visit(root.right,1)
if not root.left and not root.right and len(self.path)>=3 and len(self.path)>self.ans:
cnt=0
for i in range(2,len(self.path)):
if self.path[i]!=self.path[i-1]:
if cnt==0:
cnt+=2
else:
cnt+=1
else:
cnt=0
if len(self.path)-i<self.ans:
break
self.ans=max(self.ans,cnt)
self.path.pop()
def longestZigZag(self, root: TreeNode) -> int:
self.ans=0
if root.left or root.right:
self.ans=max(self.ans,1)
self.path=[]
self.visit(root)
return self.ans
【方法2】先序遍历,顺带两个参数在函数头,用来记录到该节点为止时,该节点来自父节点的那个分支,以及到该父节点的交错路径
的长度
目前发现这个是最简便的写法,还没有发现跟我一样的
class Solution:
def visit(self,root,loc=0,cnt=0):
if not root:
return
self.ans=max(self.ans,cnt)
self.visit(root.left,-1,(cnt+1) if (loc!=-1) else 1)
self.visit(root.right,1,(cnt+1) if (loc!=1) else 1)
def longestZigZag(self, root: TreeNode) -> int:
self.ans=0
self.visit(root)
return self.ans
【方法3】
class Solution:
def longestZigZag(self, root: TreeNode) -> int:
ans = 0
def dfs(root, l, r):
nonlocal ans
ans = max(ans, l, r)
if root.left:
dfs(root.left, r + 1, 0)
if root.right:
dfs(root.right, 0, l + 1)
dfs(root, 0, 0)
return ans