Without copy-pasting the answer, you'll want to make a Boolean tree (B-Tree), and parse it all the way through. I started writing an answer, and then I realized that there's already a perfectly good answer over hereover here. The only difference is there's some translation you'll have to do going from C# to Apex Code, which should be trivial.