简体   繁体   中英

Finding node in binary tree

Disclaimer: This is for a problem I am stuck with on a homework assignment. I need to refactor my add method and my findnodelocation method so that when finddnodelocation returns the parent node of where the new value would be added, it goes ahead and uses the add method to add the value to the binary search tree where it needs to go.

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;

}

You need to check the data IN the node, before movingo to another node. It goes like this:

// 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM