dsdf64562672 2014-03-20 08:08 采纳率: 0%
浏览 141
已采纳

递归,而不是通过return语句结束递归

I am doing binary search in this tree and expect the Find recursion to end when the result is true. It does have a result of true but even if it gets the true value and runs the return statement, it seems like continue to run and finally reach the value of false

How do I make this program end when it finds the value and returns?

http://play.golang.org/p/miWqRVo_XO

package main

import "fmt"

type Tree struct {
  Left  *Tree
  Value int64
  Right *Tree
}

func NewT(val int64) *Tree {
  return &Tree{
    Left:  new(Tree),
    Value: val,
    Right: new(Tree),
  }
}

func (T *Tree) Insert(val int64) *Tree {
  if T == nil {
    return &Tree{nil, val, nil}
  }
  if val < T.Value {
    T.Left = T.Left.Insert(val)
  } else {
    T.Right = T.Right.Insert(val)
  }
  return T
}

func (T *Tree) Find(val int64) bool {
  fmt.Printf("%v , %v
", T.Value, val)
  fmt.Printf("%v
", T.Value == val)

  if fmt.Sprintf("%v", T.Value) == fmt.Sprintf("%v", val) {
    fmt.Println("True and we do return true")
    return true
  }
  if val < T.Value {
    T.Left.Find(val)
  } else {
    T.Right.Find(val)
  }
  fmt.Println("False")
  return false
}

func main() {
  t1 := NewT(5)
  for i := 0; i < 10; i++ {
    t1 = t1.Insert(int64(i))
  }
  fmt.Println("Result:", t1.Find(7))
}

Output is

5 , 7
false
0 , 7
false
5 , 7
false
6 , 7
false
7 , 7
true
True and we do return true
  • 写回答

1条回答 默认 最新

  • douhuireng4407 2014-03-20 08:18
    关注

    You seem to be ignoring the return value of Tree.Find when you recurse into it. If you pass on the return value, you should get the desired behaviour. That is, modify the end of Find to read:

    if val < T.Value {
        return T.Left.Find(val)
    } else {
        return T.Right.Find(val)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示