You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 Void return 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 height variable: The line if height < 2 { return } references a height variable 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

  1. Added meaningful return type: T? lets the caller know exactly if a match was found, and what that match is.
  2. Removed invalid height check: We now prioritize checking the current node before recursing, which is the correct approach for tree traversal.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:04:59