108 to convert to an ordered array of binary search trees
An ordered array in accordance with the ascending order, is converted to a highly balanced binary search tree.
In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.
Example:
Given an ordered array: [-10, -3,0,5,9],
One possible answer is: [0, -3,9, -10, null, 5], it can be expressed below this height balanced binary search tree:
0
/ \
-3 9
/ /
-10 5
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums):
def to_bst(nums, start, end):
if start > end:
return None
mid = (start + end) // 2
node = TreeNode(nums[mid])
node.left = to_bst(nums, start, mid - 1)
node.right = to_bst(nums, mid + 1, end)
return node
return to_bst(nums, 0, len(nums) - 1)
2. The two numbers together
We are given two non-empty list is used to represent two non-negative integer. Where their respective bits are stored in reverse order of the way, and they each node can store only one digit.
If we add up these two numbers, it will return a new list and to represent them.
You can assume that in addition to the numbers 0, these two numbers will not begin with 0.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Cause: 342 + 465 = 807
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/add-two-numbers
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
# 2. The two numbers together (list)
class ListNode:
DEF the __init __ (Self, X):
self.val = X
self.next = None
class Solution:
DEF addTwoNumbers (Self, L1, L2):
"" "L1, l2 are ListNode "" "
Re = ListNode (0)
R & lt re # = returns pointer returns only itself
carry = 0 # records carry
the while L1 or l2:
X = L1 l1.val the else 0 IF
Y = l2 IF l2.val 0 the else
S = X + Y + with Carry
with Carry = S // 10
r.next = ListNode (10% S)
R & lt r.next =
IF L1: L1 = l1.next
IF L2: L2 = l2.next
IF with Carry> 0 :
r.next = ListNode(1)
return re.next