判斷一棵二叉樹是不是二叉排序樹

來源:互聯網
上載者:User
//判斷一棵二叉樹是不是二叉排序樹//思路:二叉排序樹的特點是,若左子樹非空,則左子樹上結點的值均小於根結點的值;//若右子樹非空,則右子樹上結點的值均大於根結點的值。所以根據這一特點,可以看出//二叉排序樹的中序遍曆是一個遞增序列。#include<iostream>#include <limits.h>using namespace std;int prev1 = INT_MIN;typedef struct BiTreeNode{int data;BiTreeNode* lchild;BiTreeNode* rchild;BiTreeNode(int x) : data(x), lchild(NULL), rchild(NULL) {}};int JudgeBST(BiTreeNode *root){int b1,b2;if(root == NULL)return 1;else{b1 = JudgeBST(root->lchild);if(b1 == 0 || prev1 >= root->data)return 0;prev1 = root->data;b2 = JudgeBST(root->rchild);return b2;}}//***********測試代碼************//           10             //         /                    //        7            //       /\               //      4  8//          \//           9void main(){    //產生一棵二叉樹    BiTreeNode* Node1 = new BiTreeNode(10);//產生節點    BiTreeNode* Node2 = new BiTreeNode(7);    BiTreeNode* Node3 = new BiTreeNode(4);    BiTreeNode* Node4 = new BiTreeNode(8);    BiTreeNode* Node5 = new BiTreeNode(9); Node1->lchild=Node2;//串連節點Node2->lchild=Node3;Node2->rchild=Node4; Node5->rchild=Node5;int p = JudgeBST(Node1);cout<<p<<endl;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.