【问题标题】:Finding node in binary tree在二叉树中查找节点
【发布时间】:2015-04-16 03:09:05
【问题描述】:

免责声明:这是针对我在家庭作业中遇到的问题。我需要重构我的 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;

}

【问题讨论】:

  • 问题不清楚。你想返回什么?深度,价值?您所说的“我如何通过返回另一个 Node 对象来返回放置节点的位置”是什么意思。 ?
  • 你想在哪里插入新节点?当第一个子节点为空时?

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多