gpt4 book ai didi

java - 在 BST 中查找节点位置并将其递归地添加到树中

转载 作者:行者123 更新时间:2023-12-01 11:38:44 25 4
gpt4 key购买 nike

所以我有 3 种方法,第一种方法使用 traverseAdd 方法将节点添加到二叉树,另一种方法根据其父节点查找值在树中放置的位置。我想消除 traverseAdd 方法并使用 add 方法中的 findLocation 方法将新值添加到 BST。

 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);
}
private void traverseAdd(Node node, Node nodeObjToAdd){
/*Traverses tree and finds a place to add the node to be added by comparing values of the left child and right child of the
* focus node*/
if(nodeObjToAdd.value < node.value){
if(node.leftChild == null){
node.leftChild = nodeObjToAdd;
}
else {
//if the val < the root.value set int he constructor
traverseAdd(node.leftChild, nodeObjToAdd);
}
}
else if(nodeObjToAdd.value > node.value) {
if (node.rightChild == null) {
node.rightChild = nodeObjToAdd;
} else {
traverseAdd(node.rightChild, nodeObjToAdd);
}
}
}
public Node findNodeLocation(Node rootNode, int val) {
/*returns where a the Node after which the value would be added.*/
if(val < rootNode.value && rootNode.leftChild != null){
return rootNode.leftChild;
}
if(val >= rootNode.value && rootNode.rightChild != null){
return rootNode.rightChild;
}
else
return this.root;

}

最佳答案

public void add(int val) {
if (root == null) {
root = new Node(val);
}
Node cur = root;
Node next = null;
while (true) {
next = findNodeLocation(cur, val);
if (next != cur) {
cur = next;
} else {
break;
}
}
if (val < cur.value) {
cur.leftChild = new Node(val);
} else {
cur.rightChild = new Node(val);
}
}

我认为这应该有效

关于java - 在 BST 中查找节点位置并将其递归地添加到树中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29733965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com