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

求助:实现基于链表的Pascal二叉搜索树递归布尔搜索函数

递归搜索带链表的Pascal二叉搜索树实现方案

嘿,我看你已经把二叉搜索树和链表的结构都定义好了,现在要写递归搜索函数返回布尔结果对吧?先得明确你的搜索目标:是找某个树节点的cod,还是找链表中的title/ISBN?我两种情况都给你写出来,你按需用就行。

情况1:搜索树节点的cod是否存在

二叉搜索树的核心特性就是左子树节点的cod都小于当前节点,右子树都大于,递归搜索就靠这个缩小范围:

function SearchTreeByCod(T: tree; TargetCod: text): Boolean;
begin
  // 递归终止:当前节点为空,肯定没找到
  if T = nil then
    SearchTreeByCod := false
  else
  begin
    // 命中目标cod,直接返回true
    if TargetCod = T^.cod then
      SearchTreeByCod := true
    // 目标比当前cod小,去左子树搜
    else if TargetCod < T^.cod then
      SearchTreeByCod := SearchTreeByCod(T^.LC, TargetCod)
    // 目标比当前cod大,去右子树搜
    else
      SearchTreeByCod := SearchTreeByCod(T^.RC, TargetCod);
  end;
end;

逻辑说明

  • 递归终止条件:当传入的树节点T为nil时,说明已经遍历到树的尽头,没有匹配到目标值,返回false。
  • 匹配成功:如果目标值和当前节点的cod完全相等,直接返回true。
  • 缩小搜索范围:根据BST左小右大的特性,分别往左子树或右子树递归搜索,逐步逼近目标值。

情况2:搜索链表中的Title或ISBN

如果你要找的是链表里面的内容(比如某个特定的ISBN),那得先写个链表的搜索辅助函数,再结合树的递归遍历:

第一步:链表的递归搜索辅助函数

function SearchListContent(L: list; TargetVal: text): Boolean;
begin
  if L = nil then
    SearchListContent := false
  else
  begin
    // 检查当前链表节点的title或ISBN是否匹配
    if (TargetVal = L^.title) or (TargetVal = L^.ISBN) then
      SearchListContent := true
    // 没匹配到就递归搜下一个链表节点
    else
      SearchListContent := SearchListContent(L^.next, TargetVal);
  end;
end;

第二步:遍历树的所有节点,检查每个节点的链表

function SearchTreeForListContent(T: tree; TargetVal: text): Boolean;
begin
  if T = nil then
    SearchTreeForListContent := false
  else
  begin
    // 先检查当前节点的链表有没有目标值
    if SearchListContent(T^.l, TargetVal) then
      SearchTreeForListContent := true
    // 当前节点没找到,去左子树搜
    else if SearchTreeForListContent(T^.LC, TargetVal) then
      SearchTreeForListContent := true
    // 左子树也没找到,去右子树搜
    else
      SearchTreeForListContent := SearchTreeForListContent(T^.RC, TargetVal);
  end;
end;

实用小提醒

  • 因为你用的是固定长度的text类型,若需要忽略大小写比较,别直接用=,换成AnsiCompareText(TargetCod, T^.cod) = 0会更灵活。
  • 如果你的树结构特别深,递归可能会触发栈溢出,但一般场景下递归写法足够用,且代码可读性更强。

内容的提问来源于stack exchange,提问作者Etto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:57:50