首页 > 代码库 > 【剑指offer】Q6:重建二叉树
【剑指offer】Q6:重建二叉树
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。