Refactor tree logic and update test cases