我有一种方法来查找二进制搜索树(BST)中的下一个中序继任者。 “inorderSuccessor”方法将BST的任何节点作为输入并输出下一个中间继承者。方法和树类的定义如下:时间使用中继方法打印BST的复杂性
class BSTInorderSuccessor{
public static Node inorderSuccessor(Node node) {
if (node.right != null) {
return minValue(node.right);
}
Node parent = node.parent;
while (parent != null && node == parent.right){
node = parent;
parent = parent.parent;
}
return parent;
}
}
class TreeNode{
int data;
Node left;
Node right;
Node parent;
public TreeNode(int data){
this.data = data;
this.left = null;
this.right = null;
this.parent = null;
}
}
假设BST的高度为h,并且此树结构中有n个节点。我知道“inorderSuccessor”方法的时间复杂度是O(h)。
我的问题是:鉴于BST的最小节点。当我编写一种方法持续调用“inorderSuccessor”来打印BST的所有节点时,总时间复杂度是多少?我认为这是O(n * h)。那是对的吗?
打印BST中的所有节点?那不是'O(* BST *中的节点数量)'吗?无论他们是按顺序,先后顺序还是其他顺序枚举? –
@AlexBollbach有一些打印方式不能在线性时间内运行,比如做一个DFS打印深度为0的所有节点,然后是深度为1的所有节点等等,所以它不是全部不合理的问题。 – templatetypedef
虽然这个问题指定了序列的使用。 –