码迷,mamicode.com
首页 > 其他好文 > 详细

【剑指offer】Q6:重建二叉树

时间:2014-07-06 00:34:00      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:algorithm   面试题   python   二叉树   

class BTNode:

	def __init__(self, val):
		self.left = None
		self.right = None
		self.val = val


'''
@ construct tree by inorder & preorder

'''
def constructByInPre(inorder, instart, inend, preorder, prestart, preend):
	if inend < instart or preend < prestart:
		return None
	if len(preorder) != len( inorder ) :
		return None
	# preorder visit: root, left, right
	for i in range(instart, inend + 1):
		if inorder[i] == preorder[prestart]: break
	if i > inend:
		print "wrong data"
		return None
	root = BTNode(inorder[i])
	root.left = constructByInPre(inorder, instart, i - 1, preorder, prestart + 1, preend)
	root.right = constructByInPre(inorder, i + 1, inend, preorder, prestart + 2, preend)
	return root



'''
@ construct tree by inorder & postorder

'''
def constructByInPost(inorder, instart, inend, postorder, posstart, posend):
	if inend < instart or posend < posstart:
		return None
	if len(postorder) != len(inorder):
		return None
	# posterorder visit: left, right, root
	for i in range(instart, inend + 1):
		if inorder[i] == postorder[posend]: break
	if i > inend:
		print "wrong data"
		return None
	root = BTNode(inorder[i])
	leftlen = i - instart
	root.left = constructByInPost(inorder, instart, i - 1, postorder, posstart, posstart + leftlen - 1)
	root.right = constructByInPost(inorder, i + 1, inend, postorder, posstart + leftlen, posend - 1)
	return root

【剑指offer】Q6:重建二叉树,布布扣,bubuko.com

【剑指offer】Q6:重建二叉树

标签:algorithm   面试题   python   二叉树   

原文地址:http://blog.csdn.net/shiquxinkong/article/details/37081309

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!