试图在二叉树中查找节点的父节点

时间:2016-11-05 21:55:31

标签: c binary-tree

我试图实现一个在二叉树中找到给定节点的父节点的函数,但该函数总是返回根节点。我不知道如何使它工作。我已经好几天了。

Tree* NodeParent(Tree* a, char c)
{
    Tree *parent = a;

    if (!EmptyTree(a))
    {
        if ((!EmptyTree(a->Left) && info(a->Left) == c)
            || (!EmptyTree(a->Right) && info(a->Right) == c))
            return parent = a;

        else
        {
            NodeParent(a->Left, c);
            NodeParent(a->Right, c);
        }
    }

    return parent;
}

另外,树结构

struct tree
{
    char c;
    Tree* Left;
    Tree* Right;
}

2 个答案:

答案 0 :(得分:0)

return a;

不是C(或者至少,它不是你认为C在这里所做的)。

你只想要像

这样的东西
package sample;

import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import javafx.scene.control.Label;

public class Controller {

    @FXML
    Canvas canvas1;

    @FXML
    Label label;

    public void onButtonPress(){
        System.out.println("test");
        Canvas canvas1 = new Canvas(300, 250);
        GraphicsContext gc = canvas1.getGraphicsContext2D();
        drawShapes(gc);
        label.setText("test");
    }

    public void drawShapes(GraphicsContext gc) {
        gc.setFill(Color.GREEN);
        gc.setStroke(Color.BLUE);
        gc.setLineWidth(5);
        gc.strokeLine(40, 10, 10, 40);
        gc.fillOval(10, 60, 30, 30);
    }
}

答案 1 :(得分:0)

您需要捕获递归调用NodeParent(a->Left, c)NodeParent(a->Right, c)的返回值...您可以尝试这样的事情:

Tree* NodeParent(Tree* a, char c) {
    Tree *parent;

    // a is empty tree -> return NULL
    if (EmptyTree(a)) {
        return NULL;

    // in this case, a is the parent
    } else if ((!EmptyTree(a->Left) && info(a->Left) == c)
        || (!EmptyTree(a->Right) && info(a->Right) == c)) {
        return a;

    // search to the left
    } else if ((parent = NodeParent(a->Left, c)) != NULL) {
        return parent;

    // search to the right
    } else if ((parent = NodeParent(a->Right, c)) != NULL) {
        return parent;

    // c not found in sub-trees
    } else {
        return NULL;
    }
}