二叉樹的遍歷:
前序遍歷:根節點->左子樹->右子樹
中序遍歷:左子樹->根節點->右子樹
後序遍歷:左子樹->右子樹->根節點
求下面樹的三種遍歷:
詳細的二叉樹的操作可以看一下我之前寫的文章前序遍歷: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: [email protected]
@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)