在二叉树中查找节点

时间:2015-04-16 03:09:06

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

免责声明:这是我在家庭作业中遇到的问题。我需要重构我的add方法和我的findnodelocation方法,以便当finddnodelocation返回将添加新值的父节点时,它会继续并使用add方法将值添加到需要去的二叉搜索树中

public void add(int val) {
        /*Adds a new node to the binary tree after traversing the tree and figuring out where it belongs*/

    Node nodeObjToAdd = new Node(val);

    if(root == null){
    //if node root is not null root = new node value
        root = nodeObjToAdd;
    }

    Node nodeTraversed = root;

    traverseAdd(nodeTraversed, nodeObjToAdd);
}

public Node findNodeLocation(Node focusNode, int val) {
/*returns where a new node with the given value will be placed based on the RootNode, and passed in value.*/
    if(val < focusNode.value && focusNode.leftChild != null){
        return focusNode.leftChild;
    }
    if(val >= focusNode.value && focusNode.rightChild != null){
        return focusNode.rightChild;
    }
    else
        return this.root;

}

1 个答案:

答案 0 :(得分:0)

在移动到另一个节点之前,您需要检查节点中的数据。它是这样的:

// Case where the data would be child of my left child
if(data < node.Data && node.leftChild != null)
    return node.leftChild.find(data);

// Case where the data would be child of my right child
if(data >= node.data && node.rigthChild != null)
    return node.rightChild.find(data);

// If it is not a child of either, then it would be added as my own child
else
   return this;
相关问题