Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic:
- ->traversed the tree.
- ->leaf node alone can't contribute in zig zag maximum path so it will return 0.
- ->zig-zag path can started from any node and in any direction,so answer
- get's updted at every node.
- ->Assume that parent of current node is the starting node of zig zag maximum path,
- then reversed direction of child of current node can only contribute in
- zig zag path.so we only returned that path zig zag's.
- '''
- # 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
- def fun(root,dir,ans):
- if root==None:
- return 0
- print(root.val, dir,ans)
- a=fun(root.left,'L',ans)
- b=fun(root.right,'R',ans)
- ans[0]=max(ans[0],max(a+1,b+1))
- if dir=='L':
- return b+1
- else:
- return a+1
- class Solution:
- def longestZigZag(self, root: Optional[TreeNode]) -> int:
- ans=[0]
- a=fun(root.left,'L',ans)
- b=fun(root.right,'R',ans)
- return max(max(a,b)+1,ans[0])-1 #reduced by 1 because edge will one less than the nodes.
Advertisement
Add Comment
Please, Sign In to add comment