判断二叉查找树的合法性 Validate Binary Search Tree
来源:互联网 发布:讯飞输入法皮肤知乎 编辑:程序博客网 时间:2024/06/12 01:39
题目: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. 题目源自于leetcode。
思路一:一个二叉树,它是二叉查找树的必要条件是中序遍历序列必须是单增序列。因此,我的方法就是判断中序遍历序列是否是递增的。我只是想判定是否是自增,因为没有必要列出整个中序遍历,只需要在中序序列添加新元素的时候判断一下是否比上一个更大即可。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isValidBST(TreeNode *root) { int pre = INT_MAX; //最初的pre设为一个特殊值 return fun(root, pre); } bool fun(TreeNode *root, int &pre) //只需要一个int来保存中序遍历序列的上一个数 { if(root != NULL) { bool left = fun(root->left, pre); if(pre != INT_MAX && pre >= root->val) //判断新增的值是否是满足增序 return false; pre = root->val; //更新序列最后一个数 bool right = fun(root->right, pre); return left && right; //返回左右子树的综合状态 } else return true; //到达空树直接返回true }};
本方法中的第二个参数pre是用于记录序列的上一个数。当然,也可以用一个全局变量来记录。
思路二:依据二叉排序树的定义递归进行。对于一个二叉排序树,左子树中所有数都比其小,右子树中所有数都比其大。递归时越往深处走,其范围限定的越是小。
class Solution {public: bool isValidBST(TreeNode *root) { return isValid(root, INT_MIN, INT_MAX); } bool isValid(TreeNode *root, int low, int high) { if(root == NULL) return true; return root->val > low && root->val < high && isValid(root->left, low, root->val) && isValid(root->right, root->val, high); }};
- 判断二叉查找树的合法性 Validate Binary Search Tree
- 【LeetCode】Validate Binary Search Tree 二叉查找树的判断
- Validate Binary Search Tree 有效的二叉查找树
- Validate Binary Search Tree 二叉搜索树的合法判断
- Validate Binary Search Tree--判断一个树是不是二叉查找树(重重重)
- 二叉查找树——Validate Binary Search Tree
- Leetcode 98 Validate Binary Search Tree 验证二叉查找树
- lintcode validate-binary-search-tree 验证二叉查找树
- **[Lintcode]Validate Binary Search Tree 验证二叉查找树
- 【LeetCode】Validate Binary Search Tree 验证二叉查找树
- 【判断二叉搜索树】Validate Binary Search Tree
- 【LeetCode】98. Validate Binary Search Tree 解法,中序遍历,搜索二叉树合法性
- LeetCode(Validate Binary Search Tree) 判断一个二叉树是否是二叉搜索树
- 判断给定二叉树是否是二叉搜索树(LeetCode: Validate Binary Search Tree)
- 95.Validate Binary Search Tree-验证二叉查找树(中等题)
- [理解leetcode解法]98. Validate Binary Search Tree 判断是否二分查找树
- [leetcode]Validate Binary Search Tree (判断有效二叉搜索树 C语言实现)
- 98. Validate Binary Search Tree(判断合法二叉搜索树)
- js 正则表达式
- 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少.请编程实现。提示:可声明1个数组 按照规律为每1个元素赋值.
- 从“执行”看领度软件和其他企业2.0以及传统OA软件的区别
- 云计算基金
- asmack实现端到端的消息回执(XEP-0184: Message Delivery Receipts)
- 判断二叉查找树的合法性 Validate Binary Search Tree
- Linux帮助命令
- C#根据IP地址获取城市
- PHP 进阶(五)AJAX
- Java用户界面
- 求某年某月某日是该月的第几天
- Linux上mount 挂载windows共享文件权限问题
- xshell颜色配置方案
- ORACLE 中ROWNUM用法总结!