go - Recursion, and not ending the recursion by return statement -
i doing binary search in tree , expect find recursion end when result true. have result of true if gets true value , runs return statement, seems continue run , reach value of false
how make program end when finds value , 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\n", t.value, val) fmt.printf("%v\n", t.value == val) if fmt.sprintf("%v", t.value) == fmt.sprintf("%v", val) { fmt.println("true , 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) := 0; < 10; i++ { t1 = t1.insert(int64(i)) } fmt.println("result:", t1.find(7)) }
output
5 , 7 false 0 , 7 false 5 , 7 false 6 , 7 false 7 , 7 true true , return true
you seem ignoring return value of tree.find
when recurse it. if pass on return value, should desired behaviour. is, modify end of find
read:
if val < t.value { return t.left.find(val) } else { return t.right.find(val) }
Comments
Post a Comment