#仅仅为自己学习使用,请勿做他用
#从尾到头打印链表
class Solution:
def printLinkedListFromHeadToTail(self,linkedList):
if not linkedList:
if linkedList.next!=None:
self.printLinkedListFromHeadToTail(linkedList.next)
print(linkedList.next.val)
class Solution:
def printLinkedListFromHeadToTail(self, linkedList):
res=[]
if not linkedList:
if not linkedList.next:
res.append(linkedList.next.val)
print(res[::-1])
#替换空格
class Solution:
def replaceSpace(self,strIn):
if strIn ==None or len(strIn)<1:
return ""
s=list(strIn)
p1=len(s)-1
scount=0
for i in s:
if i==' ':
scount+=1
s+=[None]*(scount*2)
p2=len(s)-1
while p1>=0:
if s[p1]==' ':
for i in ['%','2','0']:
s[p2]=i
p2-=1
else:
s[p2] = i
p2 -= 1
p1-=1
return "".join(s)
a=3//2
print(a)
#各种遍历二叉树
class Solution:
def preInConsTree(self,pre,Ins):
if not pre or not Ins:
return None
root=TreeNode(pre[0])
val=Ins.index(pre[0])
root.left=self.preInConsTree(pre[1:val+1],Ins[:val])
root.left=self.preInConsTree(pre[val+1:],Ins[val+1:])
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''先序遍历'''
#先序遍历(非递归法1)
def preOrder(root):
"""
:type root: TreeNode
:rtype: List[int]
"""
'''
思路分析:
preOrder每次都将遇到的节点压入栈,当左子树遍历完毕后才从栈中弹出最后一个访问的节点,访问其右子树。
在同一层中,不可能同时有两个节点压入栈,因此栈的大小空间为O(h),h为二叉树高度。
时间方面,每个节点都被压入栈一次,弹出栈一次,访问一次,复杂度为O(n)。
'''
if root == None:
return []
stack = []
result = []
while root or stack:
while root: # 从根节点开始,一直找它的左子树
result.append(root.val)
stack.append(root)
root = root.left # while结束表示当前节点为空,即前一个节点没有左子树了
root = stack.pop()
root = root.right # 开始查看它的右子树
return result
# 先序遍历(非递归法2)
def preOrder2(root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
stack = [root]
result = []
while stack:
result.append(root.val)
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
root = stack.pop()
return result
'''中序遍历'''
def inorder(root):
"""
:type root: TreeNode
:rtype: List[int]
"""
'''
思路分析(利用栈实现):
1. 使用一个栈保存结点(列表实现);
2. 如果结点存在,入栈,然后将当前指针指向左子树,直到为空;
3. 当前结点不存在,则出栈栈顶元素,并把当前指针指向栈顶元素的右子树;
4. 栈不为空,则循环步骤2、3。
'''
if root == None:
return []
stack = []
result = []
while root or stack:
if root:
s