通过使用这种BST插入方法,我只有root作为输出,为什么?

时间:2019-06-20 21:07:34

标签: java algorithm data-structures binary-search-tree

我试图使用递归插入二进制搜索树,然后使用此特定代码按顺序打印它,但是我只有root作为输出,这是为什么,因为每次弹出(每次调用后)删除新节点?(这是Java代码)

-- create function for updates to track history
CREATE function update_history ()
RETURNS TRIGGER
as $$
BEGIN   
    IF NEW.discipline <> OLD.discipline THEN
    INSERT INTO history
        (ShiftId, fieldName, OldValue, NewValue)
    VALUES(New.shift_id, 'discipline', OLD.discipline, NEW.discipline);
    END IF;
return null; -- notice return outside the IF block
END;
$$
language plpgsql;


-- create trigger for my table after updates are made to the working table
create trigger update_history_trigger
after update on working
for each row execute PROCEDURE update_history();

1 个答案:

答案 0 :(得分:0)

之所以只为输出获得一个整数,是因为第一个Insert调用正确地将元素添加到树中,但是随后的调用失败了,因为您将数据成员temp覆盖为{ {1}}递归插入到左侧或右侧时。因此,第一个null语句的第二个分支永远不会执行。

这里实际上不需要变量if。常见的约定是拥有一个私有的递归成员函数,该函数将树的根作为参数来返回修改后的树,并在公共成员函数中将返回值分配给temp

root

这意味着您只需要像public void Insert(int value) { root = Insert(root, value); } private node Insert(node r, int value) { if (r == null) { r = new node(value); } else if (value > r.data) { r.right = Insert(r.right, value); } else { r.left = Insert(r.left, value); } return r; } 这样来称呼它即可。