博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
判断一颗二叉树是不是二叉排序树BST
阅读量:6991 次
发布时间:2019-06-27

本文共 939 字,大约阅读时间需要 3 分钟。

hot3.png

#include 
#include 
//二叉树结点typedef struct binary_tree_node_t{ binary_tree_node_t * left; binary_tree_node_t * right; int  elem;};//如果是BST, 其中序遍历应该是从小到大的顺序int lastVisit = INT_MIN;int judge_BST(binary_tree_node_t * root){ if(root == NULL){ return 1; } int judgeLeft = judge_BST(root->left);//先判断左子树 if( (root->elem >= lastVisit) && judgeLeft == 1){//当前结点比上次访问的数值要大 lastVisit = root->elem; }else{ return 0; } int judgeRight = judge_BST(root->right);//最后右子树 return judgeRight;}//判断一颗二叉树是不是二叉排序树int main(){ binary_tree_node_t ns[10]; for(int i = 1; i <= 6; i++){ binary_tree_node_t tmp; tmp.elem  = i; tmp.left = NULL;//必须显式初始化为NULL tmp.right = NULL; ns[i] = tmp; } binary_tree_node_t root; root.elem = 4; root.left = &ns[2]; root.right = &ns[5]; ns[2].left = &ns[1]; ns[2].right = &ns[3];   ns[5].right = &ns[6]; printf("%d\n", judge_BST(&root)); return 0;}

转载于:https://my.oschina.net/kaneiqi/blog/308865

你可能感兴趣的文章