5.3.3—二叉查找树—Validate Binary Sear Tree

来源:互联网 发布:mmd双人动作数据 编辑:程序博客网 时间:2024/06/08 09:19
描述
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:

#include "BinaryTree.h"#include<algorithm>#include<vector>#include<stack>using namespace std;vector<int> path;//===判断二叉树是否为BSTbool IsBST(BinaryTreeNode *proot){if ((proot->m_pLeft==NULL&&proot->m_pRight==NULL)||proot==NULL)return true;if (proot->m_pLeft != NULL&&proot->m_pRight != NULL){return (proot->m_pLeft->m_nValue < proot->m_nValue&&proot->m_nValue < proot->m_pRight->m_nValue)&& IsBST(proot->m_pLeft) && IsBST(proot->m_pRight);}else if (proot->m_pLeft != NULL&&proot->m_pRight == NULL){return (proot->m_pLeft->m_nValue < proot->m_nValue)&& IsBST(proot->m_pLeft);}else if (proot->m_pLeft == NULL&&proot->m_pRight != NULL){return (proot->m_nValue < proot->m_pRight->m_nValue)&& IsBST(proot->m_pRight);}}// ====================测试代码====================//            9//        6     10//      3   8  //    1  5//  0int main(){//===BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);BinaryTreeNode* pNode3 = CreateBinaryTreeNode(3);BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);BinaryTreeNode* pNode1 = CreateBinaryTreeNode(1);BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);BinaryTreeNode* pNode0 = CreateBinaryTreeNode(0);ConnectTreeNodes(pNode9, pNode6, pNode10);ConnectTreeNodes(pNode6, pNode3, pNode8);ConnectTreeNodes(pNode3, pNode1, pNode5);ConnectTreeNodes(pNode1, pNode0, NULL);//===//PrintTree(pNode8);//===bool flag = IsBST(pNode9);cout << flag << endl;DestroyTree(pNode8);}

阅读全文
0 0