Sword refers to offer16
Title description:
Implement the function double Power(double base, int exponent), and find the exponent power of base. Do not use library functions, and do not need to consider the issue of large numbers.
Example:
Answer:
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0:
return 0
res = 1
if n < 0:
x, n = 1 / x, -n
while n:
if n & 1:
res *= x
x *= x
n >>= 1
return res
Sword refers to offer18
Title description:
Given the head pointer of the singly linked list and the value of a node to be deleted, define a function to delete the node.
Return the head node of the deleted linked list.
Example:
answer:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
cur=head
if cur.val==val:
return head.next
while cur:
if cur.next.val==val:
cur.next=cur.next.next
return head
cur=cur.next
Sword refers to offer24
Title description:
Define a function, input the head node of a linked list, reverse the linked list and output the head node of the reversed linked list.
Example:
Answer:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
res=None
while head:
res,res.next,head=head,res,head.next
return res
Sword refers to offer26
Title description:
Enter two binary trees A and B to determine whether B is a substructure of A. (It is agreed that an empty tree is not a substructure of any tree)
B is a substructure of A, that is, A has the same structure and node value as B.
For example:
given tree A:
3
/ \
45
/
12
given tree B:
. 4
/
. 1
returns true, because a subtree B and A have the same configuration and the node values.
Example:
Answer:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
if not A or not B:
return False
return self.isInclude(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
def isInclude(self, A, B):
if not B:
return True
if not A:
return False
if A.val != B.val:
return False
return self.isInclude(A.left, B.left) and self.isInclude(A.right, B.right)
Sword refers to offer27
Topic description:
Please complete a function, input a binary tree, and the function outputs its mirror image.
Such as input:
4
/
27
/ \ /
1369
image output:
4
/
72
/ \ /
9631
Example:
Answer:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if root==None:
return None
root.left,root.right=root.right,root.left
self.mirrorTree(root.left)
self.mirrorTree(root.right)
return root