สมมติว่าเรามีลำดับการข้ามผ่านสองลำดับ Preorder และ Postorder เราต้องสร้างไบนารีทรีจากสองลำดับนี้ ดังนั้นหากลำดับคือ [1,2,4,5,3,6,7], [4,5,2,6,7,3,1] ผลลัพธ์จะเป็น

เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
- ans :=สร้าง tree node โดยรับค่า pre[0], stack :=empty stack และแทรก ans
- i :=1 และ j :=0
- ในขณะที่ i <ความยาวของก่อน และ j <ความยาวของโพสต์
- ถ้าค่าสูงสุดของสแต็ก =โพสต์[j] ให้เพิ่ม j ขึ้น 1 ป๊อปอัพจากสแต็กแล้วทำซ้ำต่อไป
- node :=สร้างโหนดต้นไม้ที่มีค่า pre[i]
- หากด้านซ้ายของโหนดบนสุดของสแต็กว่างเปล่า ให้ตั้งค่าด้านซ้ายของโหนดบนสุดของสแต็กเป็นโหนด มิฉะนั้น ให้ตั้งค่าด้านขวาของโหนดบนสุดสแต็กเป็นโหนด
- แทรกโหนดลงในสแต็ก
- เพิ่ม i ขึ้น 1
- คืนสินค้า
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
ตัวอย่าง
class TreeNode:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def height(root):
if root is None:
return 0
else :
# Compute the height of left and right subtree
l_height = height(root.left)
r_height = height(root.right)
#Find the greater one, and return it
if l_height > r_height :
return l_height+1
else:
return r_height+1
def print_given_level(root, level):
if root is None:
return
if level == 1:
print(root.data,end = ',')
elif level > 1 :
print_given_level(root.left , level-1)
print_given_level(root.right , level-1)
def level_order(root):
print('[', end = '')
h = height(root)
for i in range(1, h+1):
print_given_level(root, i)
print(']')
class Solution(object):
def constructFromPrePost(self, pre, post):
"""
:type pre: List[int]
:type post: List[int]
:rtype: TreeNode
"""
ans = TreeNode(pre[0])
stack = [ans]
i = 1
j = 0
while i < len(pre) and j < len(post):
if stack[-1].data == post[j]:
j+=1
stack.pop(-1)
continue
node = TreeNode(pre[i])
if not stack[-1].left:
stack[-1].left = node
else:
stack[-1].right = node
stack.append(node)
i+=1
return ans
ob = Solution()
pre = [1,2,4,5,3,6,7]
post = [4,5,2,6,7,3,1]
tree = ob.constructFromPrePost(pre, post)
level_order(tree) อินพุต
[1,2,4,5,3,6,7] [4,5,2,6,7,3,1] pre = [1,2,4,5,3,6,7] post = [4,5,2,6,7,3,1]
ผลลัพธ์
[1,2,3,4,5,6,7,]