Advertisement
varun1729

Untitled

May 3rd, 2023
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. from collections import deque
  2.  
  3. class TreeNode:
  4.     def __init__(self, val=0, left=None, right=None):
  5.         self.val = val
  6.         self.left = left
  7.         self.right = right
  8.  
  9. def constructTree(nodes):
  10.     if not nodes:
  11.         return None
  12.    
  13.     root = TreeNode(nodes[0])
  14.     q = deque()
  15.     q.append(root)
  16.     i = 1
  17.    
  18.     while q and i < len(nodes):
  19.         parent = q.popleft()
  20.         leftVal = nodes[i]
  21.         rightVal = nodes[i+1] if i+1 < len(nodes) else None
  22.         i += 2
  23.        
  24.         if leftVal is not None:
  25.             parent.left = TreeNode(leftVal)
  26.             q.append(parent.left)
  27.        
  28.         if rightVal is not None:
  29.             parent.right = TreeNode(rightVal)
  30.             q.append(parent.right)
  31.    
  32.     return root
  33.  
  34. def maxwidth(root):
  35.     if not root:
  36.         return 0
  37.    
  38.     maxWidth = float('-inf')
  39.     q = deque()
  40.     q.append((root, 0))
  41.    
  42.     while q:
  43.         size = len(q)
  44.         left, right = float('inf'), float('-inf')
  45.        
  46.         for _ in range(size):
  47.             node, pos = q.popleft()
  48.             left = min(left, pos)
  49.             right = max(right, pos)
  50.            
  51.             if node.left:
  52.                 q.append((node.left, 2 * pos))
  53.            
  54.             if node.right:
  55.                 q.append((node.right, 2 * pos + 1))
  56.        
  57.         maxWidth = max(maxWidth, right - left + 1)
  58.    
  59.     return maxWidth
  60.  
  61. # Example usage:
  62. n = int(input())
  63. nodes = list(map(int, input().split()))
  64. root = constructTree(nodes)
  65. maxWidth = maxwidth(root)
  66. print(maxWidth)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement