Swift递归闭包匹配条件问题:二叉树递归查找代码求同行审核
Fixing Your Recursive Binary Tree Search Code
Hey AndyRoid, let's walk through the issues in your current code and get it working properly for finding a matching value in a binary tree.
Key Problems in the Original Code
- No way to return results: Your function has a
Voidreturn type, so it can't communicate to the caller whether a matching value was found, or what that value is. Right now, it just runs recursively but gives no feedback. - Undefined
heightvariable: The lineif height < 2 { return }references aheightvariable that isn't defined in the current scope. Even if you had a height property, this logic doesn't make sense—you'd want to check the current node's value before bailing out early, regardless of tree height. - Incorrect traversal logic: The current logic only recurses on the right subtree if the current node meets the condition, and only the left if it doesn't. This means you'll miss most nodes in the tree—you should check the current node first, then traverse both subtrees (or follow BST rules if this is a sorted tree).
Fixed Implementation
Here's a revised version that properly returns matching values and traverses the tree correctly. I'll use an optional return type (T?) to return the first matching value, or nil if none is found:
public func findMatchingCondition(_ process: (T) -> Bool) -> T? { switch self { case .empty: return nil // Empty node has no values to check case let .node(left, value, right): // First check if the current node's value matches if process(value) { return value } // If not, check the left subtree first if let leftMatch = left.findMatchingCondition(process) { return leftMatch } // Left subtree had no matches, check the right subtree return right.findMatchingCondition(process) } }
What Changed
- Added meaningful return type:
T?lets the caller know exactly if a match was found, and what that match is. - Removed invalid height check: We now prioritize checking the current node before recursing, which is the correct approach for tree traversal.
- Fixed traversal flow: We check the current node first, then recursively search the left subtree, and finally the right subtree. This ensures we don't miss any potential matches.
If you intended this to work with a binary search tree (where values are sorted, so you can skip subtrees based on the condition), let me know—we can adjust the logic to leverage the sorted structure for more efficient searches.
内容的提问来源于stack exchange,提问作者AndyRoid
相关产品推荐
相关产品推荐

