Leetcode convert Sorted List to Binary Search tree original problem
Given an ascending one-way list, turn it into a highly balanced two-fork search tree.
Note the point:
- A two-fork search tree of the same sequence may have multiple
Example:
Input: Nums = 1->2->3
Output:
1 3
Thinking of solving problems
This is the version of the convert Sorted Array to Binary Search Tree, which can be converted to a list before being answered. If the list is solved directly, it can be seen that the list is characterized by traversal from beginning to end, because it is incremented, so that is, from small to large in turn. And the result of the middle sequence traversal of the binary search tree is an ascending sequence, so it can be constructed by the way of the middle sequence traversal of the tree.
AC Source
# Definition for singly-linked list. class listnode(object): def __init__(self, x):Self.val = x Self.next =None# Definition for a binary tree node. class TreeNode(object): def __init__(self, x):Self.val = x Self.left =NoneSelf.right =None class solution(object): def sortedlisttobst(self, head): "" : Type Head:ListNode:rtype:TreeNode "" "node, length = Head,0 whileNode:node = node.next Length + =1Self.curr = HeadreturnSelf._sortedlisttobst (0, Length-1) def _sortedlisttobst(self, left, right): ifLeft > right:return NoneMid = (left + right)//2left = Self._sortedlisttobst (left, mid-1) root = TreeNode (self.curr.val) Root.left = left Self.curr = Self.curr.next Root.right = self . _SORTEDLISTTOBST (Mid +1, right)returnRootif__name__ = ="__main__":None
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Convert Sorted List to Binary Search Tree