Advertisement
jinhuang1102

109. Convert Sorted List to Binary Search Tree

Nov 17th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.31 KB | None | 0 0
  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. #     def __init__(self, x):
  4. #         self.val = x
  5. #         self.next = None
  6.  
  7. # Definition for a binary tree node.
  8. # class TreeNode:
  9. #     def __init__(self, x):
  10. #         self.val = x
  11. #         self.left = None
  12. #         self.right = None
  13.  
  14. class Solution:
  15.     def len(self, head):
  16.         sz = 0
  17.         i = head
  18.         while i:
  19.             sz += 1
  20.             i = i.next
  21.            
  22.         return sz
  23.    
  24.     def buildTree(self, k):
  25.        
  26.         if k == 0:
  27.             return None
  28.         print(k)
  29.         root = TreeNode(0)
  30.         root.left = self.buildTree(k - (k//2) - 1)
  31.         root.right = self.buildTree(k//2)
  32.         return root
  33.            
  34.     def inorder(self, root, head):
  35.         node = root
  36.         st = []
  37.         while st or node:
  38.             if node:
  39.                 st.append(node)
  40.                 node = node.left
  41.             else:
  42.                 node = st.pop()
  43.                 node.val = head.val
  44.                 head = head.next
  45.                 node = node.right
  46.            
  47.     def sortedListToBST(self, head):
  48.         """
  49.        :type head: ListNode
  50.        :rtype: TreeNode
  51.        """
  52.         root = self.buildTree(self.len(head))
  53.         self.inorder(root, head)
  54.         return root
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement