LeetCode – Refresh – Valid Binary Search Tree

本文介绍两种方法来验证一棵二叉树是否为有效的二叉搜索树:一是通过中序遍历比较节点值;二是利用二叉搜索树的性质,设定边界值进行递归验证。

Inorder traversal the tree and compare one by one.

 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     void getTree(vector<int> &result, TreeNode *root) {
13         if (!root) return;
14         getTree(result, root->left);
15         result.push_back(root->val);
16         getTree(result, root->right);
17     }
18     bool isValidBST(TreeNode *root) {
19         if (!root) return true;
20         vector<int> result;
21         getTree(result, root);
22         for (int i = 0; i < result.size()-1; i++) {
23             if (result[i] >= result[i+1]) return false;
24         }
25         return true;
26     }
27 };

 

 

Another method is use BST properties. Then constrains two boundaries. But this does not work not. There are couple edge cases related with INT_MAX and INT_MIN;

 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     bool isValid(TreeNode *root, int lMin, int lMax) {
13         if (!root) return true;
14         if (root->val <= lMin || root->val >= lMax) return false;
15         return isValid(root->left, lMin, root->val) && isValid(root->right, root->val, lMax);
16     }
17     bool isValidBST(TreeNode *root) {
18         if (!root) return true;
19         return isValid(root, INT_MIN, INT_MAX);
20     }
21 };

 

转载于:https://www.cnblogs.com/shuashuashua/p/4364636.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值