我有一个二进制搜索树类,我想知道,使用高度变量,如何使用它来计算每个单独节点的路径长度?
例如:
S
/ \
E X
/ \
A H
\ \
C M
" E"的路径大小(高度)是1,路径大小" A"是2,路径大小" M"是3,路径大小" X"是1.如何在使用put()方法插入节点时执行此操作?
private Key key; // sorted by key
private Value val; // associated data
private Node left, right; // left and right subtrees
private int N; // number of nodes in subtree
private int height;
private Node put(Node x, Key key, Value val)
{
if (x == null) { return new Node(key, val, 1); }
x.height = -1;
int cmp = key.compareTo(x.key);
if (cmp < 0)
{
x.left = put(x.left, key, val);
}
else if (cmp > 0)
{
x.right = put(x.right, key, val);
}
else
{
x.val = val;
}
x.N = 1 + size(x.left) + size(x.right);
return x;
}
答案 0 :(得分:1)
根据定义,叶子的路径是其父级+ 1的路径。
您可以通过添加到您的方法轻松实现这一目标:
private Node put(Node x, Key key, Value val, int height){
if (x == null) { return new Node(key, val, height); }
.
.
.
}
首次来电应该是put(null,key,val,0)
只需按每次调用增加高度,例如:
x.left = put(x.left, key, val, ++height);
当然,您必须为Node构造函数添加高度。
答案 1 :(得分:1)
您可以拥有如下所示的树/节点类关系。这摆脱了尴尬的x.N = 1 +大小(x.left)+大小(x.right);因为单个节点的大小没有意义。
public class Tree<K extends Comparable<K>, V> {
private Node head;
private int size; // number of nodes in subtree
private int height;
public Node put(K key, V value) {
size++;
if (head == null) {
head = new Node(key, value, 0);
return head;
}
Node result = head.put(key, value);
if (result.height > height) {
height = result.height;
}
return result;
}
private class Node {
private K key; // sorted by key
private V value; // associated data
private Node left, right; // left and right subtrees
private int height;
public Node(K key, V value, int height) {
this.key = key;
this.value = value;
this.height = height;
}
private Node put(K key, V value) {
int cmp = key.compareTo(this.key);
if (cmp < 0) {
if (left == null) {
left = new Node(key, value, height + 1);
return left;
} else {
return left.put(key, value);
}
} else if (cmp > 0) {
if (right == null) {
right = new Node(key, value, height + 1);
return right;
} else {
return right.put(key, value);
}
} else {
this.value = value;
return this;
}
}
}
}