问题
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