2014-05-02 07:18

题目链接

原题:

boolean isBST(const Node* node) { 
// return true iff the tree with root 'node' is a binary search tree. 
// 'node' is guaranteed to be a binary tree. 
} 

  n
 / \
a   b
     \
      c

题目:检查一棵二叉树是否为二叉搜索树。

解法:二叉搜索树,就是每个节点的左边全都小于它,右边全都大于它。如果真的对于每个节点都全部检查左右边的每个节点,就做了很多重复劳动。只需要判断每个节点的左子树最靠右,和右子树最靠左的节点是否小于和大于它即可。递归过程中传递引用可以随时更新两个需要检查的值。请看代码。

代码:

  1 // http://www.careercup.com/question?id=5632735657852928
  2 #include <climits>
  3 #include <iostream>
  4 #include <sstream>
  5 #include <string>
  6 using namespace std;
  7 
  8 struct TreeNode {
  9     int val;
 10     TreeNode *left;
 11     TreeNode *right;
 12     TreeNode(int _val = 0): val(_val), left(nullptr),right(nullptr) {};
 13 };
 14 
 15 class Solution {
 16 public:
 17     bool isBST(TreeNode *root) {
 18         if (root == nullptr) {
 19             return false;
 20         }
 21         
 22         max_val = INT_MIN;
 23         res = true;
 24         first_node = true;
 25         isBSTRecursive(root);
 26         
 27         return res;
 28     };
 29 private:
 30     int max_val;
 31     bool res;
 32     bool first_node;
 33     
 34     void isBSTRecursive(TreeNode *root) {
 35         if (!res) {
 36             return;
 37         }
 38         
 39         // root is guaranteed to be not nullptr.
 40         if (root->left) {
 41             isBSTRecursive(root->left);
 42         }
 43         if (first_node || root->val > max_val) {
 44             first_node = false;
 45             max_val = root->val;
 46         } else {
 47             res = false;
 48             return;
 49         }
 50         if (root->right) {
 51             isBSTRecursive(root->right);
 52         }
 53     };
 54 };
 55 
 56 void construcTree(TreeNode *&root)
 57 {
 58     int val;
 59     stringstream sio;
 60     string s;
 61     
 62     if (cin >> s && s != "#") {
 63         sio << s;
 64         sio >> val;
 65         root = new TreeNode(val);
 66         construcTree(root->left);
 67         construcTree(root->right);
 68     } else {
 69         root = nullptr;
 70     }
 71 }
 72 
 73 void deleteTree(TreeNode *&root)
 74 {
 75     if (root == nullptr) {
 76         return;
 77     }
 78     deleteTree(root->left);
 79     deleteTree(root->right);
 80     delete root;
 81     root = nullptr;
 82 }
 83 
 84 int main()
 85 {
 86     TreeNode *root;
 87     Solution sol;
 88     
 89     while (true) {
 90         construcTree(root);
 91         if (root == nullptr) {
 92             break;
 93         }
 94         
 95         cout << (sol.isBST(root) ? "Valid BST" : "Invalid BST") << endl;
 96         
 97         deleteTree(root);
 98     }
 99     
100     return 0;
101 }

 

 posted on 2014-05-02 07:36  zhuli19901106  阅读(266)  评论(0编辑  收藏  举报