二叉树的遍历:
前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树
后序遍历:左子树->右子树->根节点
求下面树的三种遍历:
详细的二叉树的操作可以看一下我之前写的文章前序遍历:abdefgc
中序遍历:debgfac
后序遍历:edgfbca
已知前序、中序遍历,求后序遍历
前序遍历的第一个值就是根节点,然后再中序遍历中找到这个值,那么这个值的左边部分即为当前二叉树的左子树部分前序遍历结果,这个值的右边部分即为当前二叉树的右子树部分前序遍历结果。
如上图:前序a为根节点,再看中序里面的a,由于中序是(左根右),所以a的左边debgf为左子树,右边c为右子树
所以递归调用左子树:左子树的前序遍历中序遍历为:bdefg、debgf
再递归调用右子树:c、c
递归的过程:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
已知中序、后序,求前序遍历后序遍历最后一个结点即为根结点
递归的过程:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
如果是在线笔试的话直接使用下面的代码,非常好用
#-*- coding: utf-8 -*-
#!/usr/bin/python
#Filename: BTreeNode.py
'''
Created on 2011-4-11
@author: boyce
@contact: boyce.ywr@gmail.com
@version: 1.0
'''
class BTree:
'''
Represent a no in a binary tree.
'''
def __init__(self, c='/0', l=None, r=None):
'''
Initializes the node's data
'''
self.e = c
self.left = l
self.right = r
def preorderTraverse(bt):
'''
返回前序遍历结果
'''
if bt:
return '%s%s%s' % (bt.e, preorderTraverse(bt.left), preorderTraverse(bt.right))
return ''
def inorderTraverse(bt):
'''
返回中序遍历结果
'''
if bt:
return '%s%s%s' % (inorderTraverse(bt.left), bt.e, inorderTraverse(bt.right))
return '';
def postorderTraverse(bt):
'''
返回后序遍历结果
'''
if bt:
return '%s%s%s' % (postorderTraverse(bt.left), postorderTraverse(bt.right), bt.e)
return ''
def printBTree(bt, depth):
'''
递归打印这棵二叉树,*号表示该节点为NULL
'''
'''
if not bt:
ch = '*'
else:
ch = bt.e
'''
#ch=(lambda x: (x and x.e) or '*')(bt)
ch = bt.e if bt else '*'
if(depth > 0):
print '%s%s%s' % ((depth - 1) * ' ', '--', ch)
else:
print ch
if not bt:
return
printBTree(bt.left, depth + 1)
printBTree(bt.right, depth + 1)
def buildBTreeFromPreIn(preo, ino):
'''
根据前序和中序遍历结果重构这棵二叉树
'''
if(preo == '' or ino == ''):
return None
pos = ino.find(preo[0])
if(pos < 0):
return None
return BTree(preo[0], buildBTreeFromPreIn(preo[1:pos + 1], ino[0:pos]), buildBTreeFromPreIn(preo[pos + 1:], ino[pos + 1:]))
#return nd
def buildBTreeFromInPost(ino, po):
'''
根据中序和后序遍历结果重构这棵二叉树
'''
if(ino == '' or po == ''):
return None
pos = ino.find(po[-1])
if(pos < 0):
return None
return BTree(po[-1], buildBTreeFromInPost(ino[0:pos], po[0:pos]), buildBTreeFromInPost(ino[pos + 1:], po[pos:-1]))
if __name__ == '__main__':
preo = 'ABDGCEFH'
ino = 'DGBAECHF'
po = 'GDBEHFCA'
bt = buildBTreeFromPreIn(preo, ino)
print 'Build from preorder & inorder'
print 'Preorder: %s' % (preorderTraverse(bt))
print 'Inorder: %s' % (inorderTraverse(bt))
print 'Postorder: %s' % (postorderTraverse(bt))
print 'The BTree is (* means no such a node):'
printBTree(bt, 0)
bt = buildBTreeFromInPost(ino, po)
print 'Build from inorder & postorder'
print 'Preorder: %s' % (preorderTraverse(bt))
print 'Inorder: %s' % (inorderTraverse(bt))
print 'Postorder: %s' % (postorderTraverse(bt))
print 'The BTree is (* means no such a node):'
printBTree(bt, 0)
http://blog.youkuaiyun.com/hinyunsin/article/details/6316185