Skip to content

Commit

Permalink
剑指offer 题目提交
Browse files Browse the repository at this point in the history
  • Loading branch information
darrenzhang1007 committed Feb 19, 2020
1 parent 97fdcfd commit ca03105
Show file tree
Hide file tree
Showing 3 changed files with 130 additions and 0 deletions.
42 changes: 42 additions & 0 deletions ArrayList/数组中只出现一次的数字/FindNumsAppearOnce.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
# 如果两个数相同,那么这两个数的异或操作就等于0
if len(array) < 2:
return None

twoNumXor = None
for num in array:
if twoNumXor is None:
twoNumXor = num
else:
twoNumXor = twoNumXor ^ num

count = 0 # 两个异或结果之后的最后一个1的下标
while twoNumXor % 2 == 0:
twoNumXor = twoNumXor >> 1
count += 1
mask = 1 << count

firstNum = None
secondNum = None
for num in array:
if mask & num == 0:
if firstNum is None:
firstNum = num
else:
firstNum = firstNum ^ num
else:
if secondNum is None:
secondNum = num
else:
secondNum = secondNum ^ num

return firstNum, secondNum


if __name__ == '__main__':
s = Solution()
print(s.FindNumsAppearOnce([1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, 7]))
File renamed without changes.
88 changes: 88 additions & 0 deletions Tree/tree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None


# 递归形式
def preOrderRecusive(root):
"""先根遍历
:param root: tree
:return:
"""
if root is None:
return None
print(root.val)
preOrderRecusive(root.left)
preOrderRecusive(root.right)


def midOrderRecusive(root):
"""中根遍历
:param root: tree
:return:
"""
if root is None:
return None
midOrderRecusive(root.left)
print(root.val)
midOrderRecusive(root.right)


def latOrderRecusive(root):
"""后根遍历
:param root: tree
:return: 后根遍历的值
"""
if root is None:
return None
latOrderRecusive(root.left)
latOrderRecusive(root.right)
print(root.val)


# 非递归形式:递归和循环可以相互转换;跟栈结构很像
# 非递归形式都可以将递归的内容以栈的形式转换成非递归形式。
def preOrder(root):
if root is None:
return None
stack = [] # 栈
tmpNode = root
while tmpNode or stack:
while tmpNode:
print(tmpNode.val)
stack.append(tmpNode)
tmpNode = tmpNode.left

node = stack.pop()
tmpNode = node.right


# 对于深度优先: 先序遍历 中序遍历 后序遍历
if __name__ == '__main__':
t1 = TreeNode(1)
t2 = TreeNode(2)
t3 = TreeNode(3)
t4 = TreeNode(4)
t5 = TreeNode(5)
t6 = TreeNode(6)
t7 = TreeNode(7)
t8 = TreeNode(8)

t1.left = t2
t1.right = t3
t2.left = t4
t2.right = t5
t3.left = t6
t3.right = t7
t6.right = t8
#
# preOrderRecusive(t1)
# print('--' * 30)
# midOrderRecusive(t1)
# print('--' * 30)
# latOrderRecusive(t1)
# print('--' * 30)

preOrder(t1)

0 comments on commit ca03105

Please sign in to comment.