面试常见程序题python版——持续更新中

本文介绍了二叉树的前序、中序、后序遍历的非递归实现,并提供了Python代码示例。此外,还展示了字符串处理、链表操作、排序算法等实用代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树的遍历递归和非递归 Python版本

https://blog.youkuaiyun.com/john_xyz/article/details/79342846

前序遍历非递归

def preOrder(self, root):
    if root == None:
        return
    stack = []
    node = root
    while node or stack:
        while node:
            # 从根节点开始,一直找它的左子树
            print(node.val)
            stack.append(node)
            node = node.left
        # while结束表示当前节点node为空,即前一个节点没有左子树了
        node = stack.pop()
        # 开始查看它的右子树
        node = node.right

中序遍历非递归

def inOrder(self,root):
    if root == None:
        return
    stack = []
    while node or stack:
        while node:
            # 从根节点开始,一直找到左子树
            stack.append(node)
            node = node.left
        # while结束表示当前节点node为空,即前一个节点没有左子树了
        node = stack.pop()
        print(node.val)
        node = node.right

后序遍历非递归

def postOrder(self,root):
    if root == None:
        return
    stack1 = []
    stack2 = []
    node = root
    stack1.append(node)
    while stack1:
    # 这个while循环用户找到后续遍历的逆序,存在stack2中
        node = stack1.pop()
        if node.left:
            stack1.append(node.left)
        if node.right:
            stack1.append(node.right)
        stack2.append(node)
    while stack2:
        print(stack2.pop().val)

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

public class Solution {
    public String replaceSpace(StringBuffer str) {
        String sti=str.toString();
        char[] strChar=sti.toCharArray();
        StringBuffer strb=new StringBuffer();
        for(int i=0;i<strChar.length;i++){
            if (strChar[i]==' '){
                strb.append("%20");
            }else {
                strb.append(strChar[i]);
            }

        }
        return strb.toString();
    }
}

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回二维列表,内部每个列表表示找到的路径
    def FindPath(self, root, expectNumber):
        # write code here
        if not root:
            return []
        if root and not root.left and not root.right and root.val==expectNumber:
            return [[root.val]]
        left=self.FindPath(root.left,expectNumber-root.val)
        right=self.FindPath(root.right,expectNumber-root.val)
        res=[]
        for i in left+right:
            res.append([root.val]+i)
        return res

https://blog.youkuaiyun.com/MoreWindows/article/details/6668714

#coding:utf8
#归并排序
#合并两个有序数组ab 到c
def merge(a,b):
    i=j=0
    c=[]
    while i<len(a)and j<len(b):
        if a[i]<b[j]:
            c.append(a[i])
            i+=1
        else:
            c.append(b[j])
            j+=1
    while i<len(a):
        c.append(a[i])
        i+=1
    while j<len(b):
        c.append(b[j])
        j+=1
    return c
def mergeSort(lists):
    if len(lists)<=1:
        return lists
    mid=len(lists)/2
    left=mergeSort(lists[:mid])
    right=mergeSort(lists[mid:])
    return merge(left,right)
a = [4, 7, 8, 3, 5, 9]
print mergeSort(a)

 

# coding:utf8
# #冒泡排序
def bubble_sort(lists):
    count=len(lists)
    for i in range(0,count):
        for j in range(i,count):
            if lists[i]>lists[j]:
                t=lists[i]
                lists[i]=lists[j]
                lists[j]=t
    return lists
lists=[2,4,6,7,9]
print lists
#链表打印
def traversal(head):
    curNode=head
    while curNode is not None:
        print curNode.data
        curNode=curNode.next

#binary二分查找
def binary_find(find,lists):
    low=0
    high=len(lists)
    while low<=high:
        mid=(low+high)/2
        if lists[mid]==find:
            return mid
        elif lists[mid]>find:
            high=mid-1
        else:
            low=mid+1
    return -1
lists=[2,4,6,7,9]
print binary_find(9,lists)
#字符串逆序
s="hello"
li=list(s)
li.reverse()
print "".join(li)
#字典按value值逆序
d = {'a':1,'b':4,'c':2}
print sorted(d.items(),key=lambda x:x[1],reverse=False)
#快速排序
def partition(v,left,right):
    key=v[left]
    low=left
    high=right
    while low<high:
        while (low<high)and(v[high]>=key):
            high -=1
        v[low]=v[high]
        while (low<high)and(v[low]<=key):
            low +=1
        v[high]=v[low]
        v[low]=key
    return low
def quick_sort(v,left,right):
    if left<right:
        p=partition(v,left,right)
        quick_sort(v,left,p-1)
        quick_sort(v,p+1,right)
        return v
v=[2,1,8,4,5,6]
v1=quick_sort(v,0,len(v)-1)
print v1

操作1:m=s ;s=s+s

操作2:s=s+m

初始化:s="a";m=s

给定一个字符串长度n最少需要几次操作才能获得最后的结果

测试用例:n=4 返回2

number = int(raw_input("Enter a number: "))
def test(number):

    r = []
    while number != 1:

        for i in range(1, number + 1):
            if (number % i) == 0 and i != 1:
                number = number / i
                if number == 1:
                    # print " %d" %i
                    r.append(i)
                else:
                    # print " %d*" %i,
                    r.append(i)
                break
    count = 0
    count1 = 0
    count2 = 0
    for i in r:
        if i == 2:
            count += 1
        elif i == 3:
            count1 += 2
        else:
            count2 += (i-1)
    return (count+count1+count2)
test(number)

思路:将两个字符串a,b转换成列表,以第二个字符串b的长度作为滑动窗口的长度进行滑动,将结果以字典形式存起来,key值是a列表下标,value值就是滑动窗口在a列表上获得的长度为len(b_list)子列表.

#KMP字符串匹配。给你两个字符串,寻找其中一个字符串是否包含另一个字符串,如果包含,返回包含的起始位置
def ngrams(input,n):
    output = {}
    for i in range(len(input)-n+1):
        output.setdefault(i,input[i:i+n])#{i:[]}
    return output
def find(a,b):
    a_list=list(a)
    b_list=list(b)
    n=len(b_list)
    a_dict=ngrams(a_list,n)
    for k,v in a_dict.items():
        if v==b_list:
            return k
        else:
            continue
    return -1
a=raw_input("a:")
b=raw_input("b:")
k=find(a,b)
print k

树的路径

# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        paths=[]
        if not root:return paths
        leftPaths,rightPaths=[],[]
        leftPaths=self.binaryTreePaths(root.left)
        rightPaths=self.binaryTreePaths(root.right)
        for path in leftPaths:
            print path
            a=str(root.val)+"->"+str(path)
            paths.append(a)
        for path in rightPaths:
            a = str(root.val) + "->" + str(path)
            paths.append(a)
        if(len(paths)==0):
            paths.append(""+str(root.val))
        return paths

翻转链表

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead or not pHead.next:
            return pHead
        head=pHead
        pre=None
        while head:
            Next=head.next
            head.next=pre
            pre=head
            head=Next
        return pre
#递归版本字符串反转
def func(s):
    if len(s) <1:
        return s
    return func(s[1:])+s[0]
#非递归
str[::-1]

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值