python遍历树

1.python 二叉树是怎么实现的

#coding:utf-8

#author:Elvis

class TreeNode(object):

def __init__(self):

self.data = '#'

self.l_child = None

self.r_child = None

class Tree(TreeNode):

#create a tree

def create_tree(self, tree):

data = raw_input('->')

if data == '#':

tree = None

else:

tree.data = data

tree.l_child = TreeNode()

self.create_tree(tree.l_child)

tree.r_child = TreeNode()

self.create_tree(tree.r_child)

#visit a tree node

def visit(self, tree):

#输入#号代表空树

if tree.data is not '#':

print str(tree.data) + '\t',

#先序遍历

def pre_order(self, tree):

if tree is not None:

self.visit(tree)

self.pre_order(tree.l_child)

self.pre_order(tree.r_child)

#中序遍历

def in_order(self, tree):

if tree is not None:

self.in_order(tree.l_child)

self.visit(tree)

self.in_order(tree.r_child)

#后序遍历

def post_order(self, tree):

if tree is not None:

self.post_order(tree.l_child)

self.post_order(tree.r_child)

self.visit(tree)

t = TreeNode()

tree = Tree()

tree.create_tree(t)

tree.pre_order(t)

print '\n'

tree.in_order(t)

print '\n'

tree.post_order(t)

2.python怎么用递归遍历多层目录树

Python实现递归遍历指定文件目录(startdir),从而找到所有与指定的文件或目录(target)名相同的文件或目录的绝对路径。

scandir.py :#! /usr/bin/python# filename : scandir.py# author : Jesse# update : 2011/08/15 10:16import osdef scandir(startdir, target) : os.chdir(startdir) for obj in os.listdir(os.curdir) : if obj == target : print os.getcwd() + os.sep + obj if os.path.isdir(obj) : scandir(obj, target) os.chdir(os.pardir) #!!!startdir = raw_input('Please input startdir: ')target = raw_input('Please input target: ')scandir(startdir, target)关于该程序的一点说明:1. 函数scandir的形参target可以是目录名也可以是文件名。2. 函数chdir的作用是切换到指定目录,该参数必须是有效的且有访问权限的相对路径或绝对路径。

3. 函数的第五行,使用getcwd函数也是为了取得当前绝对路径。4. 加号作为字符串的连接符。

os.sep根据你的操作系统给出目录分隔符,在GNU/Linux和UNIX上它的返回值是'/',在windows上它的返回值是'\\',在Mac OS上是‘:’,使用os.sep而不直接使用字符,会提高程序的可移植性。5. 递归调用后,一定不能忘了os.chdir(os.pardir),返回上层目录(即父目录)。

重要:1. 理解for中的两个并列的if语句,并列是为了解决目标是文件夹时,该目标文件夹中包含符合要求的文件夹。2. 如果指定目录中存在访问受限的文件或文件夹,该程序会失败,返回无权访问信息。

3.求一个python的三叉树算法

这是网络上的一个版本,我自己做了一点修改,这是一个n叉树,希望对你有所帮助#!/usr/bin/python # -*- coding: utf-8 -*- '''Created on 2014-3-26@author: qcq''' #============================================================================== # tree.py: Generic tree node object for Python #==============================================================================#--# $Revision: 1.7 $# $Date: 2000/03/29 22:36:12 $# modified by qcq in 2014/3/27# modified by qcq in 2014/4/23 增加了遍历树的非递归版本的广度优先和深度优先#--#================================================================# Contents#----------------------------------------------------------------# class Tree: Generic n-ary tree node object# class NodeId: Represents the path to a node in an n-ary tree#----------------------------------------------------------------#import stringclass Tree: """ Generic n-ary tree node object Children are additive; no provision for deleting them. The birth order of children is recorded: 0 for the first child added, 1 for the second, and so on. modified by qcq in 2014/3/27. add the function for deleting one node in the tree structure Exports: Tree(parent, value=None) Constructor .parent If this is the root node, None, otherwise the parent's Tree object. .childList List of children, zero or more Tree objects. .value Value passed to constructor; can be any type. .birthOrder If this is the root node, 0, otherwise the index of this child in the parent's .childList .nChildren() Returns the number of self's children. .nthChild(n) Returns the nth child; raises IndexError if n is not a valid child number. .fullPath(): Returns path to self as a list of child numbers. .nodeId(): Returns path to self as a NodeId. """# - - - T r e e . _ _ i n i t _ _ - - - def __init__ ( self, parent, value=None ): """ Constructor for a Tree object. [ if (parent is None or a Tree object) -> if (parent is None) -> return a new Tree object with no parent, no children, and value (value) else -> return a new Tree object added as the next new child of parent (parent) and no children, and value (value) ] """ #-- 1 -- self.parent = parent self.value = value self.childList = [] #-- 2 -- #-[ if (parent is None) -> # self.birthOrder := 0 # else -> # parent := parent with self added as its next child # self.birthOrder := size of parent's .childList #-] if parent is None: self.birthOrder = 0 else: self.birthOrder = len(parent.childList) parent.childList.append ( self )# - - - T r e e . n C h i l d r e n - - - def nChildren ( self ): """ [ return the number of children of self ] """ return len(self.childList)# - - - T r e e . n t h C h i l d - - - def nthChild ( self, n ): """ [ if (n is an integer) -> if (0 return self's (n)th child, counting from 0 else -> raise IndexError ] """ return self.childList[n]# - - - T r e e . f u l l P a t h - - - def fullPath ( self ): """Returns a list of child numbers from root to self. [ return a sequence [c0, c1, 。

, ci] such that self is root.nthChild(c0).nthChild(c1). 。 .nthChild(ci), or an empty list if self is the root ] """ #-- 1 -- result = [] parent = self.parent kid = self #-- 2 -- # [ result +:= child numbers from parent to root, in # reverse order ] while parent: result.insert ( 0, kid.birthOrder ) parent, kid = parent.parent, parent #-- 3 -- return result# - - - T r e e . n o d e I d - - - def nodeId ( self ): """Returns the path to self in the tree as a NodeId. """ #-- 1 -- # [ fullPath := sequence [c0, c1, 。

, ci] such that self is # root.nthChild(c0).nthChild(c1). 。 .nthChild(ci), or # an empty list if self is the root ] fullPath = self.fullPath() #-- 2 -- return NodeId ( fullPath ) def equals(self, node): '''judge if the two tree object is equal ''' return self.value == node.value #=========================================================================== # delete the node from the tree #=========================================================================== def delete(self): if self.parent is None: return else: #temp = self.birthOrder ''' if delete the middle tree object, then move the tree object behind this tree object forward. ''' self.parent.childList.remove(self.parent.childList[self.birthOrder]) for i,j in zip(range(self.birthOrder + 1, self.parent.nChildren()), self.parent.childList[self.birthOrder + 1:]): j.birthOrder = j.birthOrder - 1 def update(self, value): ''' update the value of this Tree object ''' self.value = value def __str__(self): return "The %d child with value %d"%(self.birthOrder, self.value)# - - - - - c l a s s N o d e I d - - - - -class NodeId: """Represents the location of a node in a tree as a path from the root. Exports: NodeId(path): [ if path is a list of zero or more nonnegative integers -> return a new NodeId object representing that node-id ] .path: [ as passed to 。

4.求Python二叉树的几个算法 求几个二叉树的method! 1) 给一个值,然

你好:二叉树算法,网上是比较多的;可能按照你的需求不是很多:下面是我用的一个,不过你可以借鉴一下的:# -*- coding: cp936 -*-import osclass 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 = parentclass 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.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.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。

5.python 怎么遍历 dict 的keys

看到有人回答,但是不太全,如果遍历dict有如下机种方式:

d是dict()类型

1:for key in d:

print key,d[key]

2:for key in d.keys():

print key,d[key]

3:for key,value in d.items():

print key,value

4. for key,value in d.iteritems():

print key,value

5. for key in d.iterkeys():

print key,d[key]

6.求一个python的三叉树算法

这是网络上的一个版本,我自己做了一点修改,这是一个n叉树,希望对你有所帮助 #!/usr/bin/python # -*- coding: utf-8 -*- '''Created on 2014-3-26@author: qcq''' #============================================================================== # tree.py: Generic tree node object for Python #==============================================================================#--# $Revision: 1.7 $# $Date: 2000/03/29 22:36:12 $# modified by qcq in 2014/3/27# modified by qcq in 2014/4/23 增加了遍历树的非递归版本的广度优先和深度优先#--#================================================================# Contents#----------------------------------------------------------------# class Tree: Generic n-ary tree node object# class NodeId: Represents the path to a node in an n-ary tree#----------------------------------------------------------------#import stringclass Tree: """ Generic n-ary tree node object Children are additive; no provision for deleting them. The birth order of children is recorded: 0 for the first child added, 1 for the second, and so on. modified by qcq in 2014/3/27. add the function for deleting one node in the tree structure Exports: Tree(parent, value=None) Constructor .parent If this is the root node, None, otherwise the parent's Tree object. .childList List of children, zero or more Tree objects. .value Value passed to constructor; can be any type. .birthOrder If this is the root node, 0, otherwise the index of this child in the parent's .childList .nChildren() Returns the number of self's children. .nthChild(n) Returns the nth child; raises IndexError if n is not a valid child number. .fullPath(): Returns path to self as a list of child numbers. .nodeId(): Returns path to self as a NodeId. """# - - - T r e e . _ _ i n i t _ _ - - - def __init__ ( self, parent, value=None ): """ Constructor for a Tree object. [ if (parent is None or a Tree object) -> if (parent is None) -> return a new Tree object with no parent, no children, and value (value) else -> return a new Tree object added as the next new child of parent (parent) and no children, and value (value) ] """ #-- 1 -- self.parent = parent self.value = value self.childList = [] #-- 2 -- #-[ if (parent is None) -> # self.birthOrder := 0 # else -> # parent := parent with self added as its next child # self.birthOrder := size of parent's .childList #-] if parent is None: self.birthOrder = 0 else: self.birthOrder = len(parent.childList) parent.childList.append ( self )# - - - T r e e . n C h i l d r e n - - - def nChildren ( self ): """ [ return the number of children of self ] """ return len(self.childList)# - - - T r e e . n t h C h i l d - - - def nthChild ( self, n ): """ [ if (n is an integer) -> if (0 <= n < (number of self's children) -> return self's (n)th child, counting from 0 else -> raise IndexError ] """ return self.childList[n]# - - - T r e e . f u l l P a t h - - - def fullPath ( self ): """Returns a list of child numbers from root to self. [ return a sequence [c0, c1, 。

, ci] such that self is root.nthChild(c0).nthChild(c1). 。 .nthChild(ci), or an empty list if self is the root ] """ #-- 1 -- result = [] parent = self.parent kid = self #-- 2 -- # [ result +:= child numbers from parent to root, in # reverse order ] while parent: result.insert ( 0, kid.birthOrder ) parent, kid = parent.parent, parent #-- 3 -- return result# - - - T r e e . n o d e I d - - - def nodeId ( self ): """Returns the path to self in the tree as a NodeId. """ #-- 1 -- # [ fullPath := sequence [c0, c1, 。

, ci] such that self is # root.nthChild(c0).nthChild(c1). 。 .nthChild(ci), or # an empty list if self is the root ] fullPath = self.fullPath() #-- 2 -- return NodeId ( fullPath ) def equals(self, node): '''judge if the two tree object is equal ''' return self.value == node.value #=========================================================================== # delete the node from the tree #=========================================================================== def delete(self): if self.parent is None: return else: #temp = self.birthOrder ''' if delete the middle tree object, then move the tree object behind this tree object forward. ''' self.parent.childList.remove(self.parent.childList[self.birthOrder]) for i,j in zip(range(self.birthOrder + 1, self.parent.nChildren()), self.parent.childList[self.birthOrder + 1:]): j.birthOrder = j.birthOrder - 1 def update(self, value): ''' update the value of this Tree object ''' self.value = value def __str__(self): return "The %d child with value %d"%(self.birthOrder, self.value)# - - - - - c l a s s N o d e I d - - - - -class NodeId: """Represents the location of a node in a tree as a path from the root. Exports: NodeId(path): [ if path is a list of zero or more nonnegative integers -> return a new NodeId object representing 。

python遍历树

转载请注明出处代码入门网 » python遍历树

资讯

eclipsepython插件

阅读(8)

本文主要为您介绍eclipsepython插件,内容包括如何在eclipse中安装python的插件,eclipse怎么装python插件,如何为eclipse安装合适版本的python插件pydev。安装完Pydev插件之后,有时我们会发现知在Window -> Preferences下并没有PyDev选项,这是

资讯

pythondict的keys

阅读(9)

本文主要为您介绍pythondict的keys,内容包括pythondict.keys是什么类型,python怎么遍历dict的keys,Python中如何以dict的key排序输出。看到有人回答,但是不太全,如果遍历dict有如下机种方式:d是dict()类型1:for key in d:print key,d[ke

资讯

python树的遍历

阅读(8)

本文主要为您介绍python树的遍历,内容包括python二叉树先序遍历什么意思,python怎么用递归遍历多层目录树,求一个python的三叉树算法。Python实现递归遍历指定文件目录(startdir),从而找到所有与指定的文件或目录(target)名相同的文件或目录的绝

资讯

python官网

阅读(8)

本文主要为您介绍python官网,内容包括python3.4.0官网怎么下,如何安装python,python官网安装选择哪个。首先,需要到python的官方网站下载python的安装包。2、打开官方网站之后,点击“Downloads”一栏,然后在弹出的窗口选择“

资讯

python和php

阅读(9)

本文主要为您介绍python和php,内容包括python与php的区别是什么,php和python哪个更有前途在国内的未来,Python和PHP有什么区别。输出、数据类型、访问权限、定义变量和方法不同输出Python: print 默认换行,不换行要加逗号。PHP: echo 可以输

资讯

python写入xml

阅读(9)

本文主要为您介绍python写入xml,内容包括如何用Python创建生成xml文档文件的方法,如何用Python创建生成xml文档文件的方法,python解析xml,包含中文,gb2312编码修改xml后重新写入xml有些。内存数据产生 2、产生xml内存对象(也就是DOM树) 3、产

资讯

pythonif判断语句

阅读(7)

本文主要为您介绍pythonif判断语句,内容包括刚自学python,用if判断语句怎么编写个程序,,pythonif语句可以多条件判断么,pythonif语句可以多条件判断么。i=1时,第二个for语句执行n次;i=2时,第二个for语句执行n-1次;i=3时,第二个for语句执行n-2次.

资讯

pythonmac教程

阅读(7)

本文主要为您介绍pythonmac教程,内容包括pythonmac版怎么使用,怎么在mac上使用python,mac怎么运行python。如果要使用 Python 2 来运行此文件,因为 OS X 自带 Python 2,所以直接输入1搜索python "python"文件

资讯

python3.6formac

阅读(7)

本文主要为您介绍python3.6formac,内容包括mac怎么安装python3.6,mac怎么安装python3.6,如何在mac下使用python3。启动python查看Mac自带python的路径:终端输入$ which python打开路径在Finder中进入路径 /usr/bin

资讯

python程序调用

阅读(8)

本文主要为您介绍python程序调用,内容包括python如何程序调用,怎么调用编写好的python程序,怎么调用编写好的python程序。PLAYER_1 = "C:\Program Files\Tencent\QQMusic\QQMusic.exe" file = r"D

资讯

python简易

阅读(7)

本文主要为您介绍python简易,内容包括求一个简单的Python程序在线等,求帮我编一个简单的python程序,python简单小程序。==========这个是某次应求帮人写的程序================原始连接:http://zhidao.baidu.com/

资讯

listpython重复

阅读(8)

本文主要为您介绍listpython重复,内容包括如何找出pythonlist中有重复的项,python方法可让list中的元素重复N次,python里的list可以重复么。可以对第二个list的元素进行遍历,检查是否出现在第二个list当中,如果使用表理解,可以使用一行代码完

资讯

pythonclose

阅读(6)

本文主要为您介绍pythonclose,内容包括python中close的用法,为什么会出现attributeerror&#39;str&#39;objecthason,Python在打开文件后为什么要close(),如果不关有什么危害搜,python中涉及到文件的程序,为什么close函数是必须的。python 对

资讯

pythonclusterby

阅读(5)

本文主要为您介绍pythonclusterby,内容包括pythonsubplots是什么意思,pythonscipy怎么做层次聚类,udaf可以用python写吗。group和groups是两个不同的函数。一般,m.group(N) 返回第N组括号匹配的字符。而m.group() == m.grou

资讯

eclipsepython插件

阅读(8)

本文主要为您介绍eclipsepython插件,内容包括如何在eclipse中安装python的插件,eclipse怎么装python插件,如何为eclipse安装合适版本的python插件pydev。安装完Pydev插件之后,有时我们会发现知在Window -> Preferences下并没有PyDev选项,这是

资讯

pythondict的keys

阅读(9)

本文主要为您介绍pythondict的keys,内容包括pythondict.keys是什么类型,python怎么遍历dict的keys,Python中如何以dict的key排序输出。看到有人回答,但是不太全,如果遍历dict有如下机种方式:d是dict()类型1:for key in d:print key,d[ke

资讯

python树的遍历

阅读(8)

本文主要为您介绍python树的遍历,内容包括python二叉树先序遍历什么意思,python怎么用递归遍历多层目录树,求一个python的三叉树算法。Python实现递归遍历指定文件目录(startdir),从而找到所有与指定的文件或目录(target)名相同的文件或目录的绝

资讯

python官网

阅读(8)

本文主要为您介绍python官网,内容包括python3.4.0官网怎么下,如何安装python,python官网安装选择哪个。首先,需要到python的官方网站下载python的安装包。2、打开官方网站之后,点击“Downloads”一栏,然后在弹出的窗口选择“

资讯

python和php

阅读(9)

本文主要为您介绍python和php,内容包括python与php的区别是什么,php和python哪个更有前途在国内的未来,Python和PHP有什么区别。输出、数据类型、访问权限、定义变量和方法不同输出Python: print 默认换行,不换行要加逗号。PHP: echo 可以输

资讯

python写入xml

阅读(9)

本文主要为您介绍python写入xml,内容包括如何用Python创建生成xml文档文件的方法,如何用Python创建生成xml文档文件的方法,python解析xml,包含中文,gb2312编码修改xml后重新写入xml有些。内存数据产生 2、产生xml内存对象(也就是DOM树) 3、产

资讯

pythonif判断语句

阅读(7)

本文主要为您介绍pythonif判断语句,内容包括刚自学python,用if判断语句怎么编写个程序,,pythonif语句可以多条件判断么,pythonif语句可以多条件判断么。i=1时,第二个for语句执行n次;i=2时,第二个for语句执行n-1次;i=3时,第二个for语句执行n-2次.

资讯

linux服务器python

阅读(7)

本文主要为您介绍linux服务器python,内容包括linux下使用python访问服务器中文件,在linux服务器上同时安装python2.6和python3,如何在linux服务器上用PHP执行python脚本。我估计你用的是centos吧,因为centos的yum以来python2.6,所以默认安装

资讯

毕业设计python

阅读(1)

本文主要为您介绍毕业设计python,内容包括用python做毕业设计,做个什么题目稍微容易一点,用Python做毕业设计选什么项目比较好,刚刚接触python,正好赶上毕设,想做python,由于是新手,所以想拜。首先你选择Python就很好,且不说Python本身很简

资讯

pythonlinux开发

阅读(1)

本文主要为您介绍pythonlinux开发,内容包括如何在linux下开发python程序,pycharm怎么开发linux程序,linux和python先学哪个。众所周知,系统管理员需要精通一门脚本语言,而且招聘机构列出的职位需求上也会这么写。大多数人会认为 Bash (或者其

资讯

python上海

阅读(1)

本文主要为您介绍python上海,内容包括上海python培训学费多少钱老男孩培训机构多少钱,想学习python,麻烦问一下上海哪家比较好一点的培训机构有这个课程,上海python就业前景是否值得期待。优点 门槛低,上手快; 2、比 R 更具有通用性和实用性

资讯

python程序运行时

阅读(1)

本文主要为您介绍python程序运行时,内容包括分析python程序运行时间的几种方法,python的程序怎么运行,如何运行Python程序。你在windows下根本不用这么麻烦: 首先,比如你的程序名字是 test.py 如果你想调用某个具体函数,就自己写一个的文件,比

资讯

python在线编译

阅读(1)

本文主要为您介绍python在线编译,内容包括python在线编译器哪个,求一个好的免费的Python编译器,最好是直接丢链接,谢谢大佬,什么软件可以编译Python。实际上python 是脚本语言解释执行的,并不存在编译这个概念。用python -m py_compile file

资讯

pythonascii字符

阅读(1)

本文主要为您介绍pythonascii字符,内容包括python判断纯ASCII字符串怎么做,如何使用Python获得一个字符的ASCII值,python怎么判断ascii字符串问题。如果要判断某路径是否包换中文,可以用正则表达式判断是否含有双字节字符>>> import re>>> r

资讯

python进程通信

阅读(1)

本文主要为您介绍python进程通信,内容包括python进程间通信怎么理解,python进程间通信怎么理解,python进程间通信怎么理解。在2.6才开始使用multiprocessing 是一个使用方法类似threading模块的进程模块。允许程序员做并行开发。并且可以在

资讯

eclipse运行python

阅读(1)

本文主要为您介绍eclipse运行python,内容包括如何在eclipse中运行python,如何在eclipse中运行python,怎么用eclipse打开python项目。下载python下载eclipse假设有上面两个,下载一个Python的Eclipse插件pydev下载完后将其解压到Eclipse的目

资讯

python类的self

阅读(1)

本文主要为您介绍python类的self,内容包括python怎么理解类和self的用法和含义,python怎么理解类和self的用法和含义,python中self是什么意思。python的class保留了语言在进化过程中的一些遗迹。对象这种概念,可以追溯到C语言中大量使用的结

资讯

数组长度python

阅读(1)

本文主要为您介绍数组长度python,内容包括python数组要先定义长度吗,python数组要先定义长度吗,python如何输入一个长度不定的数组。视情况而定如果你的数来组是追加一个元素的可以不用定义长度如果你初始化一个列自表然后要修改其中的值的