This is my insertion method right now. It is working somewhat, but not for every test case I throw at it. I mainly want these fields in node because I need to implement these 2 methods. I understand I can iterate over the tree and recalculate these values , but I am told not to. Any tips?
int height(Integer key): return the height of the node containing the given key or -1 if the key is not in the tree.
int size(Integer key): return the number of nodes in the subtree whose root contains the given key or -1 if the tree does not contain the key
private int height; private node root; private int treeSize; public void put(Integer key, String val){ node tmpNode = new node(key,val); if(root == null){ root = tmpNode; height++; treeSize++; }else{ node curr = root; node parent; while(true){ parent = curr; if(key.equals(curr.key)){ curr.val = val; return; } if(key < curr.key){ curr = curr.left; if(curr == null){ treeSize++; root.N = treeSize; parent.left = tmpNode; parent.left.nodeHeight = parent.nodeHeight + 1; parent.N += parent.left.N + 1; if(height < parent.left.nodeHeight){ height = parent.left.nodeHeight; } return; } }else{ curr = curr.right; if(curr == null){ treeSize++; root.N = treeSize; parent.right = tmpNode; parent.right.nodeHeight = parent.nodeHeight + 1; parent.N += parent.right.N + 1; if(height < parent.right.nodeHeight){ height = parent.right.nodeHeight; } return; } } } } } //Node class class node{ Integer key; String val; int nodeHeight; int N; node right; node left; public node(Integer key, String val){ this.key = key; this.val = val; this.N = 1; } public String toString(){ return key + " " + val; } }
https://stackoverflow.com/questions/66947804/how-to-keep-track-of-a-nodes-height-and-size-of-subtree-of-that-particular-node April 05, 2021 at 11:07AM
没有评论:
发表评论