bool isVaildBST(TreeNode *root, TreeNode * & pre) { if(root!=NULL) { if(root->left) if(!isVaildBST(root->left,pre)) { return false; } if(pre!=NULL) { if(pre->val >= root->val) return false; } pre = root; if(root->right) if(!isVaildBST(root->right,pre)) { return false; } return true; } else return true; }
// HW8.C5 // 구현방법 : 노드의 leftChild와 rightChild값이 타당한지 확인하고 타당하면 1을 리턴하는 함수를 재귀적으로 구현 int isVaildBST(node_t *node) { if(!node) return 1; // node가 없어도 BST이므로 & 리프노드에서 1 리턴 if(node->leftChild && node->leftChild->key > node->key) return 0; if(node->rightChild && node->rightChild->key < node->key) return 0; if(!isVaildBST(node->leftChild) || !isVaildBST(node->rightChild)) return 0; return 1; }
void testIsValidBST(node_t *node) { if (isVaildBST(node)) { printf("Valid BST\n"); } else { printf("Invalid BST\n"); } }
bool isValidBST(TreeNode *root) { TreeNode * pre = NULL; return isVaildBST(root,pre); }