大家好:我讀了下面的算法,找到二叉搜索樹中兩個節點的最小公共祖先。爲什麼這個算法的空間複雜度是O(1)
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int);
/* Function to find least comman ancestor of n1 and n2 */
int leastCommanAncestor(struct node* root, int n1, int n2)
{
/* If we have reached a leaf node then LCA doesn't exist
If root->data is equal to any of the inputs then input is
not valid. For example 20, 22 in the given figure */
if(root == NULL || root->data == n1 || root->data == n2)
return -1;
/* If any of the input nodes is child of the current node
we have reached the LCA. For example, in the above figure
if we want to calculate LCA of 12 and 14, recursion should
terminate when we reach 8*/
if((root->right != NULL) &&
(root->right->data == n1 || root->right->data == n2))
return root->data;
if((root->left != NULL) &&
(root->left->data == n1 || root->left->data == n2))
return root->data;
if(root->data > n1 && root->data < n2)
return root->data;
if(root->data > n1 && root->data > n2)
return leastCommanAncestor(root->left, n1, n2);
if(root->data < n1 && root->data < n2)
return leastCommanAncestor(root->right, n1, n2);
}
需要注意的是上述函數假定N1比N2小。 時間複雜度:O(n)的空間複雜度:O(1)
這個算法是遞歸的,我知道,調用遞歸函數調用時,函數參數和其他相關的寄存器被壓入堆棧,所以另一方面,需要額外的空間,另一方面,遞歸深度與樹的大小或高度有關,比如n,它是否更有意義是O(n)?
感謝您在這裏的任何解釋!
堆棧通常(當樹是大體平衡)不超過_O(log n)的_空間。 – Svante 2010-10-20 16:10:04