For a given binary tree, assuming that the value of each node is different, design an algorithm to determine whether the binary tree is a binary sort tree

For a given binary tree, assuming that the value of each node is different, design an algorithm to determine whether the binary tree is a binary sort tree

The first
algorithm idea:
traverse the binary tree and compare each node with the value of the left and right child nodes of the node. Because the value of each node is different, so if the value of the left child node is greater than that of the node If the value or the value of the right child node is less than the value of the node, the binary tree is not a binary sort tree, otherwise the comparison continues until the traversal is completed.
Algorithm implementation:

bool Func(node *T){
    
    
	if(T){
    
    
		if(NULL == T->lChild&&NULL == T->rChild){
    
    
			return true;
		}else if(NULL == T->lChild){
    
    
			if(T->data < T->rChild->data){
    
    
				return Func(T->rChild);
			}else{
    
    
				return false;
			}
		}else if(NULL == T->rChild){
    
    
			if(T->data > T->lChild->data){
    
    
				return Func(T->lChild);
			}else{
    
    
				return false;
			}
		}else{
    
    
			if(T->data < T->rChild->data&&T->data > T->lChild->data){
    
    
				return (Func(T->rChild)&&Func(T->lChild);
			}else{
    
    
				return false;
			}
		}
	}
}

The second
algorithm idea:
If the middle-order traversal sequence is increasing, the binary tree is a binary sort tree, otherwise it is not. (The in-order sequence of the binary sort tree is a non-descending sequence)

Guess you like

Origin blog.csdn.net/qq_45800517/article/details/106242626