标签:int div ali cli btree return sub mamicode init
题目:
解法:
方法一:
下面是brute force code,虽然不是很高效,但是可以工作。
1 bool isSubTreeLessThan(BinaryTree *p, int val) 2 { 3 if (!p) 4 { 5 return true; 6 } 7 return (p->data < val && isSubTreeLessThan(p->left, val) && isSubTreeLessThan(p->right, val)); 8 } 9 10 bool isSubTreeGreaterThan(BinaryTree *p, int val) 11 { 12 if (!p) 13 { 14 return true; 15 } 16 return (p->data > val && isSubTreeGreaterThan(p->left, val) && isSubTreeGreaterThan(p->right, val)); 17 } 18 19 bool isBSTBruteForce(BinaryTree *p) 20 { 21 if (!p) 22 { 23 return true; 24 } 25 return isSubTreeLessThan(p->left, p->data) && isSubTreeGreaterThan(p->right, p->data) 26 && isBSTBruteForce(p->left) && isBSTBruteForce(p->right); 27 }
方法二:
1 /** 2 * Definition for a binary tree node. 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 bool isBSTHelper(TreeNode *p, int low, int high) 13 { 14 if (p == NULL) 15 { 16 return true; 17 } 18 if (low < p->val && p->val < high) 19 { 20 return isBSTHelper(p->left, low, p->val) && isBSTHelper(p->right, p->val, high); 21 } 22 else 23 { 24 return false; 25 } 26 } 27 28 bool isValidBST(TreeNode *root) 29 { 30 // INT_MIN and INT_MAX are defined in C++‘s <climits> library 31 return isBSTHelper(root, INT_MIN, INT_MAX); 32 } 33 };
方法三:
1 //小集合和大集合均OK 2 class Solution 3 { 4 public: 5 bool isBSTInOrderHelper(TreeNode *p, int& prev) 6 { 7 if(p == NULL) 8 { 9 return true; 10 } 11 12 if(isBSTInOrderHelper(p->left, prev)) 13 { 14 if(prev < p->val) 15 { 16 prev = p->val; 17 18 return isBSTInOrderHelper(p->right, prev); 19 } 20 else 21 { 22 return false; 23 } 24 } 25 else 26 { 27 return false; 28 } 29 } 30 31 bool isBSTInOrder(TreeNode *root) 32 { 33 int prev = INT_MIN; 34 return isBSTInOrderHelper(root, prev); 35 } 36 37 //main 38 bool isValidBST(TreeNode *root) 39 { 40 if(root == NULL) 41 { 42 return true; 43 } 44 else 45 { 46 return isBSTInOrder(root); 47 } 48 } 49 };
标签:int div ali cli btree return sub mamicode init
原文地址:https://www.cnblogs.com/ocpc/p/12817379.html