Symmetric Tree

Leetcode considers this question to be easy, but it was a bit more complicated than that at first for me. Let’s try solving it three different ways: Whenever I can, I always try to do BFS. It seems much more natural. BFS - 1st solution func isSymmetricBFS(_ root: TreeNode?) -> Bool { var queue: [TreeNode?] = [] queue.append(root) while !queue.isEmpty { let temp = queue queue.removeAll() // 🔑 to make sure you don't expand on `nil` nodes — otherwise it would be endless for node in temp where node !...

January 12, 2025 · 2 min

Tree Basics and some Swift helpers for leetcode

I do leetcoding every once a while, but keep forgetting some tree basics. This post here it to help with that. Node vs Side 💡 This was a very subtle yet “Aha” moment for me. When you’re traversing down a tree using dfs, while you can do things like: let leftNode = process(node.left) let rightNode = process(node.right) it might be better to see at as: let leftSide = process(node.left) let rightSide = process(node....

September 11, 2023 · 9 min