BST设置每个指向节点的高度

BST setting height at each pointing node

本文关键字:节点 高度 设置 BST      更新时间:2023-10-16

我正在尝试实现递归方法,以递归方式设置每个节点的高度。部分解决方案已经实现,但我不完全确定在哪里可以减少高度并检查Order遍历中的特定节点是否完成。我的程序基于此实现:http://visualgo.net/bst.html

感谢

如果这里的高度表示节点所在的树的级别,那么使用全局变量会产生非常奇怪的结果。我也承认,我不完全确定你在用变量u做什么。

也就是说,我认为你应该接受这样的东西:

public void setHeight(struct node *r, int h = -1) {
    // pointer pointing to null, return
    if(r == NULL)  {
        return;
    }
    h++; // increment height
    r.height = h; // set update height to a current node
    setHeight(r ->u.lc, h); // traverse the list pointing to the left child
    visit(r) // visit pointing node
    setHeight(r ->u.rc, h); // visit right child of the node
}

编辑:我还没有发表评论的资格,所以我只能用编辑来回应@ProgLearner,您不需要单独的变量u,因为您的节点指针是一个函数参数,因此每次调用函数时都会有一个新的变量。类似地,正如Jonathan Mee所说,h变量不需要外部初始化,因为它也是函数的本地变量。在没有提供任何初始值的情况下(比如在根上调用它时),它将默认为-1。