BST insert
上的所有实现都是非尾递归的。
是否可以为BST编写尾部递归插入?
如果有可能,怎么样?
答案 0 :(得分:4)
可能:例如,在continuation-passing style中写insert
函数。
e.g。在Racket
#lang racket
(struct bst-node (left right value) #:transparent)
(define (insert tree new-value)
(insert-cps tree new-value (lambda (x) x)))
(define (insert-cps tree new-value cont)
(cond
[(empty? tree) (cont (bst-node empty empty new-value))]
[else (match-let ([(bst-node l r v) tree])
(cond
[(= v new-value) (cont (bst-node l r v))]
[(< new-value v) (insert-cps l new-value (lambda (t) (cont (bst-node t r v))))]
[else (insert-cps r new-value (lambda (t) (cont (bst-node l t v))))]))]))
(insert (insert (insert empty 10) 15) 2)
答案 1 :(得分:0)
只需添加到解决方案中,您还可以执行以下操作(我在F#中实现):
let Insert element bst=
//find where the element need to be inserted
let mutable next = bst.Root
let rec insert n r =
match n,r with
|_ when n < r.Data && r.LeftNode.IsNone -> r
|_ when n > r.Data && r.RightNode.IsNone -> r
|_ when n = r.Data -> r
|_ -> if n < r.Data then
next <- r.LeftNode.Value
else
next <- r.RightNode.Value
insert n next
let n = insert element bst.Root
//if duplicate is found return false
if n.Data = element then
false
else //otherwise create new node
let node: BSTNode<'a> ={
Data = element
LeftNode = None
RightNode = None
}
//insert into proper postion (left or right accordingly)
if n.Data > node.Data then
n.LeftNode <- Some(node)
true
else
n.RightNode <- Some(node)
true
递归方法是尾递归,没有堆栈堆积。基本的递归方法可以找到要插入的位置。然后,如果要插入的内容还没有在树中,请简单比较一下。
答案 2 :(得分:-1)
查看此代码是否适合您。
public class TailInsertion {
class Node {
int dat;
Node left;
Node right;
Node(int dat) {
this.dat = dat;
}
}
public void insert(Node root, Node parent, int dat) {
if (root == null) {
if (parent == null) {
return;
} else {
if (parent.dat <= dat) {
parent.right = new Node(dat);
return;
} else {
parent.left = new Node(dat);
return;
}
}
}
Node node = null;
if (root.dat <= dat) {
node = root.right;
} else {
node = root.left;
}
insert(node, root, dat);
}
}
答案 3 :(得分:-1)
这尾不是递归的吗?
void insert(Tree *t, int val) {
if (t == NULL || val == t->Value) {
return;
}
Tree *next = NULL;
if (val < t->Value)
next = t->Left;
else
next = t->Right;
insert(next, val);
}