CoderJesse  
wangjiexi@CS.PKU

Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.

中序周游判断是否是排好序的即可。

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int tmp;
13     bool tag;
14     bool key;
15     bool isValidBST(TreeNode *root) {
16         // Start typing your C/C++ solution below
17         // DO NOT write int main() function
18         tag = false;
19         key = true;
20         check(root);
21         return key;
22     }
23     void check(TreeNode *root)
24     {
25         if(key == false)
26             return;
27         if(root == NULL)
28             return;
29         check(root->left);
30         if(tag == false)
31         {
32             tmp = root->val;
33             tag = true;
34         }
35         else
36         {
37             if(root->val <= tmp)
38                 key = false;
39             else
40                 tmp = root->val;
41         }
42         check(root->right);
43     }
44 };

 

posted on 2013-03-01 13:34  CoderJesse  阅读(115)  评论(0)    收藏  举报