面试题35:复杂链表的复制
- 题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
- 详细代码:
# -*- coding:utf-8 -*-
# class RandomListNode:
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if not pHead:
return None
self.CloneNodes(pHead)
self.CloneRandom(pHead)
return self.ReconnectList(pHead)
def CloneNodes(self, pHead):
pNode = pHead
while pNode:
pCloned = RandomListNode(0)
pCloned.label = pNode.label
pCloned.next = pNode.next
pNode.next = pClond
pNode = pCloned.next
def CloneRandom(self, pHead):
pNode = pHead
while pNode:
pCloned = pNode.next
if pCloned.random:
pCloned.random = pNode.random.next
pNode = pCloned.next
def ReconnectList(self, pHead):
pNode = pHead
pClonedNode = pClonedHead = pNode.next
pNode.next = pClonedNode.next
pNode = pNode.next
while pNode:
pClonedNode.next = pNode.next
pClonedNode = pClonedNode.next
pNode.next = pCloneNode.next
pNode = pNode.next
return pClonedHead
面试题36:二叉搜索树与双向链表
- 题目描述:
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
- 详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Convert(self, pRootOfTree):
# write code here
if not pRootOfTree:
return
root = pHead = pRootOfTree
while pHead.left:
pHead = pHead.left
self.ConvertCore(root)
return pHead
def ConvertCore(self, root):
if not root.left and not root.right:
return
if root.left:
preNode = root.left
self.ConvertCore(root.left)
while preNode.right:
preNode = preNode.right
preNode.right = root
root.left = preNode
if root.right:
nextNode = root.right
self.ConvertCore(root.right)
while nextNode.left:
nextNode = nextNode.left
nextNode.left = root
root.right = nextNode
面试题37:序列化二叉树
- 题目描述:
请实现两个函数,分别用来序列化和反序列化二叉树
- 详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Serialize(self, root):
# write code here
if not root:
return '#'
return str(root.val) + ',' +self.Serialize(root.left) + ',' + self.Serialize(root.right)
falg = -1
def Deserialize(self, s):
self.flag += 1
treeList = s.split(',')
if self.flag >= len(s):
return None
root = None
if treeList[self.flag] != '#':
root = TreeNode(int(treeList[self.flag]))
root.left = self.Deserialize(s)
root.right = self.Deserialize(s)
return root
面试题38:字符串的排列
- 题目描述:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
- 详细代码:
# -*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
if not ss:
return []
if len(ss) == 1:
return list(ss)
res = []
charlist = list(ss)
charlist.sort()
for i in range(len(charlist)):
if i > 0 and charlist[i] == charlist[i - 1]:
continue
temp = self.Permutation(''.join(charlist[:i]) + ''.join(charlist[i + 1:]))
for j in temp:
res.append(charlist[i] + j)
return res