简体   繁体   English

在二叉树中查找节点

[英]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. 我需要重构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;

}

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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