首先定義樹節點的數據結構,以下:node
struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; };
兩個函數,用來建立節點,以及構建樹的,這個樹的構建,咱們採用最簡單的按層次結構構造。經過一個先入先出隊列,來存儲節點的左右葉子節點。數組
struct TreeNode * createTreeNode(int val) { struct TreeNode* node = malloc(sizeof(struct TreeNode)); if (node != NULL) { node->val = val; node->left = NULL; node->right = NULL; return node; } return NULL }
#define MAXNODE 100數據結構
struct TreeNode * createBiTree(int *BiNum, int size) { struct TreeNode * Queue[MAXNODE] = {0}; int front = -1; int rear = 0; struct TreeNode *node; struct TreeNode *leftNode; struct TreeNode *rightNode; int i = 0; if (BiNum != NULL) node = createTreeNode(BiNum[i]); if (node) Queue[rear] = node; i++; while(i < size && rear != front) { leftNode = createTreeNode(BiNum[i]); front++; Queue[front]->left = leftNode; if (leftNode) { rear++; Queue[rear] = leftNode; } i++; if (i < size) { rightNode = createTreeNode(BiNum[i]); Queue[front]->right = rightNode; if (rightNode) { rear++; Queue[rear] = rightNode; } i++; } } return node; }
最後咱們寫一個函數,來斷定此二叉樹是否爲搜索二叉樹。判斷一顆樹是不是二叉搜索樹,一棵樹是BST須要知足函數
因此只須要遍歷每一個節點,判斷spa
bool isValidBST(struct TreeNode* root){ struct TreeNode* leftnode; struct TreeNode* rightnode; if (root == NULL) return true; leftnode = root->left; while(leftnode) { if (root->val <= leftnode->val) return false; leftnode = leftnode->right; } rightnode = root->right; while(rightnode) { if (root->val >= rightnode->val) return false; rightnode = rightnode->left; } if (isValidBST(root->left) && isValidBST(root->right)) return true; return false; }
最後來看下咱們如何應用這些函數,給定一個數組{5,3,7,2,4,5,8,1};用層次順序來組成一個二叉樹,而後判斷改樹是否爲一個二叉搜索樹。code
void main() { int num[8] = {5,3,7,2,4,6,8,1}; struct TreeNode * node = createBiTree(num, 8); printf("is valid BST %d", isValidBST(node)); }