简体   繁体   中英

Time Complexity of printing BST using inorder successor method

I have a method for finding the next inorder successor within a Binary Search Tree (BST). The "inorderSuccessor" method takes any node of the BST as input and output the next inorder successor. The method and tree class are defined as follow:

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

Suppose the height of the BST is h, and there are n nodes within this tree structure. I know that the time complexity of "inorderSuccessor" method is O(h).

My question is: Given the smallest node of the BST. When I write a method to continuously call "inorderSuccessor" to print all the nodes of the BST, what is the total time complexity? I think it is O(n * h). Is that correct?

You can upper-bound the cost of printing everything out by always finding the inorder successor at O(nh), but that's actually not a tight bound. You can show that the runtime is actually Θ(n), independently of the height of the tree!

One way to see this is to look at how many times each edge in the tree gets visited. If you trace out the execution of all those inorder traversals, you'll find that you go down each edge exactly once and go up each edge exactly once, and the total work done is proportional to the number of times each edge is visited. The number of edges in an n-node tree is Θ(n), hence the runtime bound.

Note that you can't say that each individual operation will take time O(1). That's not true. What you can say is that in aggregate each one takes an average of O(1) time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM