Вот рекурсивное решение Ruby
def rebuild(preorder, inorder)
root = preorder.first
root_inorder = inorder.index root
return root unless root_inorder
root.left = rebuild(preorder[1, root_inorder], inorder[0...root_inorder])
root.right = rebuild(preorder[root_inorder+1..-1], inorder[root_inorder+1..-1])
root
end
И пример
class Node
attr_reader :val
attr_accessor :left, :right
def initialize(val)
@val = val
end
def ==(node)
node.val == val
end
def inspect
"val: #{val}, left: #{left && left.val || "-"}, right: #{right && right.val || "-"}"
end
end
inorder = [4, 7, 2, 5, 1, 3, 8, 6, 9].map{|v| Node.new v }
preorder = [1, 2, 4, 7, 5, 3, 6, 8, 9].map{|v| Node.new v }
tree = rebuild(preorder, inorder)
tree
# val: 1, left: 2, right: 3
tree.left
# val: 2, left: 4, right: 5
tree.left.left
# val: 4, left: -, right: 7