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 != nil { queue.append(node?.left) queue.append(node?.right) } if isSymmetric(temp) == false { return false } } return true } BFS feels very natural because you traverse layer by layer. Here we have the logic broken down nicely: ...

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.right) Mentally for me this was a big shift in how I see it. DFS is iteratively / recursively against a path, much like how you iterate against items within an array. At each iteration of the path, you just process a single node within the path. Decide to then further continue or stop. ...

How Understanding State Machines Helps With Building Trees and Graphs

My team was dealing with a large flow, where user can transition from multiple states or sometimes skip certain states. We didn’t have a centralized controller, every screen just had logic on where it should go next. This made it difficult for us to see all our logic at once. We asked around and was told state machines are a good fit for our situation. State machines are void of any UX. You just pass an event to it. Based on the event and the current state, you update to a new state along with an optional command to act upon. ...