【leetcode】Validate Binary Search Tree
来源:互联网 发布:淘宝如何开好直通车 编辑:程序博客网 时间:2024/05/21 12:07
问题:给定一棵二叉树,判断其是否为二叉查找树。
二叉查找树的要求:
1. 若根结点不空,且存在左孩子,则该结点的值大于左孩子的值(是大于,不是大于等于)。
2.若根结点不空,且存在右孩子,则该结点的值小于右孩子的值(是小于,不是小于等于)。
3.根结点的左右子树也是二叉查找树。
分析:提到二叉查找树,我们知道其中序遍历是递增有序的,也就是说,在中根遍历中,访问到的当前根结点的值要大于中序遍历中上一次访问到的结点的值,否则得到的就不是递增有序,即不是二叉查找树。但这里说到了一个“上次访问到的结点的值”,在访问中序遍历的第一个结点时,它并不存在先前的结点,或先前的值,这就要我们给定一个初始的“先前”值。另外一个注意的是,随着访问的进行,“上一次访问到的结点的值” 要被当前访问到的结点的值替代。
public: bool visitTree(TreeNode *root, int& pre_value){if(root == NULL)return true;bool left = visitTree(root->left, pre_value);if(!left || pre_value >= root->val)return false;elsepre_value = root->val;return visitTree(root->right, pre_value);}bool isValidBST(TreeNode *root) {bool isBST = true;if( NULL == root || (NULL == root->left && NULL == root->right))return isBST;int pre_value = 0x80000000;return visitTree(root,pre_value);}
0 0
- LeetCode: Validate Binary Search Tree
- [Leetcode] Validate Binary Search Tree
- LeetCode : Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Validate binary search tree
- [LeetCode]Validate Binary Search Tree
- [Leetcode]Validate Binary Search Tree
- [leetcode]Validate Binary Search Tree
- LeetCode-Validate Binary Search Tree
- [leetcode] Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- Leetcode Validate Binary Search Tree
- LeetCode | Validate Binary Search Tree
- LeetCode - Validate Binary Search Tree
- Leetcode: Validate Binary Search Tree
- 【Leetcode】Validate Binary Search Tree
- 【leetcode】Validate Binary Search Tree
- 枚举所有打开的Office文件路径
- 如何让出色团队在享受中创造更棒的游戏
- cocos2d-x项目的开始
- 郭芳芳
- JQUERY’S JSONP EXPLAINED WITH EXAMPLES
- 【leetcode】Validate Binary Search Tree
- 同一天认要
- 每日一小练——数值自乘非递归解
- CATransform3DMakeRotation 旋转,翻转
- 【转】SQLServer汉字转全拼音函数
- facebook网站为什么如此简洁?
- 在android系统使用LitJson
- Mahout安装与配置
- vim全局替换命令