Space complexity of validation of a binary search tree

空扰寡人 提交于 2019-12-13 14:06:25

问题


The best algorithm to verify if a binary tree is a BST is given as follows

IsValidBST(root,-infinity,infinity);

bool IsValidBST(BinaryNode node, int MIN, int MAX) 
{
    if(node == null)
        return true;
    if(node.element > MIN 
        && node.element < MAX
        && IsValidBST(node.left,MIN,node.element)
        && IsValidBST(node.right,node.element,MAX))
        return true;
    else 
        return false;
}

The space complexity of this logic is apparently O(logN) which I'm assuming is the cost of recursion. How was the value arrived at?


回答1:


My comment upgraded to answer:

There is no additional data used other than the method variables and the return value, so indeed, all memory is "cost of recursion". The total cost would hence be linearly proportional to the depth of the tree.

In a balanced binary search tree, the depth is O(log n), so indeed, the space complexity would be O(log n) too. However, in general a BST is not necessarily balanced, it could even be a chain of length n, if the root is the minimum, its right child is the second smallest element, and so on. In that case the space complexity of this recursion is O(n).



来源:https://stackoverflow.com/questions/21546611/space-complexity-of-validation-of-a-binary-search-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!