Replace manual tree restructuring with pattern matching