① 一道算法题,用python初始化一颗二叉树并求解其最短路径的值
二叉树算法,可能按照你的需求不是很多:
下面是我用的一个,不过你可以借鉴一下的:
# -*- coding: cp936 -*-
import os
class Node(object):
"""docstring for Node"""
def __init__(self, v = None, left = None, right=None, parent=None):
self.value = v
self.left = left
self.right = right
self.parent = parent
class BTree(object):
"""docstring for BtTee """
def __init__(self):
self.root = None
self.size = 0
def insert(self, node):
n = self.root
if n == None:
self.root = node
return
while True:
if node.value <= n.value:
if n.left == None:
node.parent = n
n.left = node
break
else:
n = n.left
if node.value > n.value:
if n.right == None:
n.parent = n
n.right = node
break
else:
n = n.right
def find(self, v):
n = self.root # http://yige.org
while True:
if n == None:
return None
if v == n.value:
return n
if v < n.value:
n = n.left
continue
if v > n.value:
n = n.right
def find_successor(node):
'''查找后继结点'''
assert node != None and node.right != None
n = node.right
while n.left != None:
n = n.left
return n
def delete(self, v):
n = self.find(v)
print "delete:",n.value
del_parent = n.parent
if del_parent == None:
self.root = None;
return
if n != None:
if n.left != None and n.right != None:
succ_node = find_successor(n)
parent = succ_node.parent
if succ_node == parent.left:
#if succ_node is left sub tree
parent.left = None
if succ_node == parent.right:
#if succ_node is right sub tree
parent.right = None
if del_parent.left == n:
del_parent.left = succ_node
if del_parent.right == n:
del_parent.right = succ_node
succ_node.parent = n.parent
succ_node.left = n.left
succ_node.right = n.right
del n
elif n.left != None or n.right != None:
if n.left != None:
node = n.left
else:
node = n.right
node.parent = n.parent
if del_parent.left == n:
del_parent.left = node
if del_parent.right == n:
del_parent.right = node
del n
else:
if del_parent.left == n:
del_parent.left = None
if del_parent.right == n:
del_parent.right = None
def tranverse(self):
def pnode(node):
if node == None:
return
if node.left != None:
pnode(node.left)
print node.value
if node.right != None:
pnode(node.right)
pnode(self.root)
def getopts():
import optparse, locale
parser = optparse.OptionParser()
parser.add_option("-i", "--input", dest="input", help=u"help name", metavar="INPUT")
(options, args) = parser.parse_args()
#print options.input
return (options.input)
if __name__ == '__main__':
al = [23, 45, 67, 12, 78,90, 11, 33, 55, 66, 89, 88 ,5,6,7,8,9,0,1,2,678]
bt = BTree()
for x in al :
bt.insert(Node(x))
bt.delete(12)
bt.tranverse()
n = bt.find(12)
if n != None:
print "find valud:",n.value
② python编写欧式二叉树的问题
所以我就遇到了一下几个问题:
1、该怎么把二叉树各个节点连起来?
2、怎么定义内部数据成员?
3、如何实例化左右孩子?
在网上也没找到比较简单比较通用的Python二叉树类实现,所以我花了点时间自己写一个。
[python] view plain 在CODE上查看代码片派生到我的代码片
class Tree:
def __init__(self, val = '#', left = None, right = None):
self.val = val
self.left = left
self.right = right
#前序构建二叉树
def FrontBuildTree(self):
temp = input('Please Input: ')
node = Tree(temp)
if(temp != '#'):
node.left = self.FrontBuildTree()
node.right = self.FrontBuildTree()
return node#因为没有引用也没有指针,所以就把新的节点给返回回去
#前序遍历二叉树
def VisitNode(self):
print(self.val)
if(self.val != '#'):
self.left.VisitNode()
self.right.VisitNode()
if __name__ == '__main__':
root = Tree()
root = root.FrontBuildTree()
root.VisitNode()
③ python二叉树输出结果为什么是这样
1. 二叉树
二叉树(binary tree)中的每个节点都不能有多于两个的儿子。
图 ((7+3)*(5-2))的表达式树表示
2.1 根据中缀表达式构造表达式树:
遍历表达式:
1.建立一个空树
2.遇到'(',为当前的Node添加一个left child,并将left child当做当前Node。
3.遇到数字,赋值给当前的Node,并返回parent作为当前Node。
4.遇到('+-*/'),赋值给当前Node,并添加一个Node作为right child,将right child当做当前的Node。
5.遇到')',返回当前Node的parent。
defbuildexpressionTree(exp):tree=BinaryTree('')stack=[]stack.append(tree)currentTree=treeforiinexp:ifi=='(':currentTree.insertLeft('')stack.append(currentTree)currentTree=currentTree.leftChildelifinotin'+-*/()':currentTree.key=int(i)parent=stack.pop()currentTree=parentelifiin'+-*/':currentTree.key=icurrentTree.insertRight('')stack.append(currentTree)currentTree=currentTree.rightChildelifi==')':currentTree=stack.pop()else:raiseValueErrorreturntree上述算法对中缀表达式的写法要求比较繁琐,小括号应用太多,例如要写成(a+(b*c))的形式。
用后缀表达式构建表达式树会方便一点:如果符号是操作数,建立一个单节点并将一个指向它的指针推入栈中。如果符号是一个操作符,从栈中弹出指向两棵树T1和T2的指针并形成一棵新的树,树的根为此操作符,左右儿子分别指向T2和T1.
123456789101112131415defbuild_tree_with_post(exp):stack=[]oper='+-*/'foriinexp:ifinotinoper:tree=BinaryTree(int(i))stack.append(tree)else:righttree=stack.pop()lefttree=stack.pop()tree=BinaryTree(i)tree.leftChild=lefttreetree.rightChild=righttreestack.append(tree)returnstack.pop()3.树的遍历
3.1 先序遍历(preorder travelsal)
先打印出根,然后递归的打印出左子树、右子树,对应先缀表达式
12345678defpreorder(tree,nodelist=None):ifnodelistisNone:nodelist=[]iftree:nodelist.append(tree.key)preorder(tree.leftChild,nodelist)preorder(tree.rightChild,nodelist)returnnodelist3.2 中序遍历(inorder travelsal)
先递归的打印左子树,然后打印根,最后递归的打印右子树,对应中缀表达式
12345definorder(tree):iftree:inorder(tree.leftChild)printtree.keyinorder(tree.rightChild)3.3 后序遍历(postorder travelsal)
递归的打印出左子树、右子树,然后打印根,对应后缀表达式
1234567defpostorder(tree):iftree:forkeyinpostorder(tree.leftChild):yieldkeyforkeyinpostorder(tree.rightChild):yieldkeyyieldtree.key3.4 表达式树的求值
1234567891011defpostordereval(tree):operators={'+':operator.add,'-':operator.sub,'*':operator.mul,'/':operator.truediv}leftvalue=Nonerightvalue=Noneiftree:leftvalue=postordereval(tree.leftChild)rightvalue=postordereval(tree.rightChild)ifleftvalueandrightvalue:returnoperators[tree.key](leftvalue,rightvalue)else:returntree.key④ 如何用python构造一个n层的完全二叉树
用python构造一个n层的完全二叉树的代码如下:
typedefstruct{
intweight;
intparent,lchild,rchild;
}HTNode,*HuffmanTree;//动态分配数组存储huffman树
算法设计
voidcreateHuffmantree(){
ht=(HuffmanTree)malloc(m+1)*sizeof(HTNode);//动态分配数组存储huffman树,0号单元未用
//m:huffman树中的结点数(m=2*n-1)
for(i=1;i<=m;++i)
ht[i].parent=ht[i]->lch=ht[i]->rch=0;
for(i=1;i<=n;++i)
ht[i].weight=w[i];//初始化,w[i]:n个叶子的权值
for(i=n+1;i<=m,++i){//建哈夫曼树
select(i-1),s1,s2);//在ht[k](1<=k<=i-1)中选择两个双亲域为零而权值取最小的结点:s1和s2
ht[s1].parent=ht[s2].parent=i;
ht[i].lch=s1;
ht[i].rch=s2;
ht[i].weight=ht[s1].weight+ht[s2].weight;
};
}
⑤ 数据结构-二叉树的创建
#include <stdio.h>
#define ElemType char
//节点声明,数据域、左孩子指针、右孩子指针
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//先序建立二叉树
BiTree CreateBiTree(){
char ch;
BiTree T;
scanf('%c',&ch);
if(ch=='#')T=NULL;
else{
T = (BiTree)malloc(sizeof(BiTNode));
T->data = ch;
T->lchild = CreateBiTree();
T->rchild = CreateBiTree();
}
return T;//返回根节点
}
//先序遍历二叉树
void PreOrderTraverse(BiTree T){
if(T){
printf('%c',T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
//中序遍历
void InOrderTraverse(BiTree T){
if(T){
PreOrderTraverse(T->lchild);
printf('%c',T->data);
PreOrderTraverse(T->rchild);
}
}
//后序遍历
void PostOrderTraverse(BiTree T){
if(T){
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
printf('%c',T->data);
}
}
void main(){
BiTree T;
T = CreateBiTree();//建立
PreOrderTraverse(T);//输出
getch();
}
⑥ python非递归建立二叉树
class Node(object):
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class MyBST(object):
def __init__(self):
self.empty = True
def add(self, value):
if self.empty:
self.root = Node(value)
self.empty = False
cur = self.root
while (True):
if not cur:
cur = Node(value)
break
if value > cur.value:
if cur.value != None:
cur = cur.right
else:
newNode = Node(value)
cur.right = newNode
break
elif value < cur.value:
if cur.value != None:
cur = cur.left
else:
newNode = Node(value)
cur.left = newNode
break
else:
cur.value = value
break
在while(True)循环里添加一个if条件判断
⑦ Python算法之哈夫曼编码
问题: 哈夫曼编码,英文名称 Huffman Coding,有时也翻译为霍夫曼编码,在1952年提出的,是最好的编码方式。哈夫曼编码在电子通讯方面有着重要的应用,同时也广泛应用于数据压缩坦槐,其压缩率通常在20% 90%之间 赫夫曼码是可变字长编码(VLC)的一种。哈夫曼树是最优二叉树, 带权路径长度最小的二叉树。
原理:
假设有几个数字40,10,20,16,14。
首先将这五个数字按照从小到大的顺序排列:10, 14,16,20, 40。
构建哈夫曼树:
1.首先选取10,14
2.重新排序:16,20,24,40
3.重新排序24,36,40,60
4.按照二叉羡信冲树左0右1,构建哈兄歼夫曼树
所以最终得到数字10的编码为100,数字14的编码为101,数字16的编码为110,数字20的编码为111,数字40的编码为0。
代码:
运行结果: