imashutosh51

Longest zig-zag path in a binary tree

Aug 11th, 2022 (edited)
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. '''
  2. Logic:
  3. ->traversed the tree.
  4. ->leaf node alone can't contribute in zig zag maximum path so it will return 0.
  5. ->zig-zag path can started from any node and in any direction,so answer
  6.  get's updted at every node.
  7. ->Assume that parent of current node is the starting node of zig zag maximum path,
  8.  then reversed direction of child of current node can only contribute in
  9.  zig zag path.so we only returned that path zig zag's.
  10. '''
  11. # Definition for a binary tree node.
  12. # class TreeNode:
  13. #     def __init__(self, val=0, left=None, right=None):
  14. #         self.val = val
  15. #         self.left = left
  16. #         self.right = right
  17.  
  18. def fun(root,dir,ans):
  19.     if root==None:
  20.         return 0
  21.     print(root.val, dir,ans)
  22.     a=fun(root.left,'L',ans)
  23.     b=fun(root.right,'R',ans)
  24.     ans[0]=max(ans[0],max(a+1,b+1))
  25.     if dir=='L':
  26.         return b+1
  27.     else:
  28.         return a+1
  29.  
  30. class Solution:
  31.     def longestZigZag(self, root: Optional[TreeNode]) -> int:
  32.         ans=[0]
  33.         a=fun(root.left,'L',ans)
  34.         b=fun(root.right,'R',ans)
  35.         return max(max(a,b)+1,ans[0])-1 #reduced by 1 because edge will one less than the nodes.
  36.        
Advertisement
Add Comment
Please, Sign In to add comment