Validate Binary Search Tree--判断一个树是不是二叉查找树(重重重)
来源:互联网 发布:平价婚纱品牌知乎 编辑:程序博客网 时间:2024/05/03 12:42
问题:链接
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
根据二叉查找树的定义:
- 结点node的左子树所有结点的值都小于node的值。
- 结点node的右子树所有结点的值都大于node的值。
- 结点node的左右子树同样都必须是二叉搜索树。
采用递归判断,在判断一个二叉树是否是二叉查找树的同时,需要返回该二叉查找树的最大和最小值,用于父节点判断。
参考:在判断一个树是否是平衡二叉树时返回二叉树的深度。(链接)
如果该节点为空 那么直接返回 true。
如果该节点是叶子节点,返回 true, 该树的最大值和最小值都是node->val.
如果该节点的两个左右子树都是二叉查找树。
{
如果左子树为空,同时节点值小于右子树最小值。 是二叉查找树,更新Max = rightmax , min = node->val;
如果右子树为空,同时节点值大于左子树最大值。 是二叉查找树,更新max = node->val, min = leftmin;
如果左右子树都不为空,同时节点值大于左子树最大值,小于右子树最小值,是二叉树。更新max = rightmax, min = leftmin;
}
另外的几种解法:链接
还有一种中序遍历法没看懂,再看。
代码:class Solution {public: bool isValidBST(TreeNode *root) { int max, min;return isBST(root, max, min); }bool isBST(TreeNode *node, int &max, int &min){int leftmax;int leftmin;int rightmax;int rightmin;if(node == NULL)return true;if(node->left == NULL && node->right == NULL){max = node->val;min = node->val;return true;}else if(isBST(node->left, leftmax, leftmin) && isBST(node->right, rightmax, rightmin)){if(node->left == NULL && node->val < rightmin){max = rightmax;min = node->val;return true;}else if(node->right == NULL && node->val > leftmax){max = node->val;min = leftmin;return true;}else if(leftmax < node->val && node->val < rightmin){max = rightmax;min = leftmin;return true;}return false;}else{return false;}}};
0 0
- Validate Binary Search Tree--判断一个树是不是二叉查找树(重重重)
- 判断二叉查找树的合法性 Validate Binary Search Tree
- 【LeetCode】Validate Binary Search Tree 二叉查找树的判断
- LeetCode(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 验证二叉查找树
- Balanced Binary Tree --判断平衡二叉树(重重)
- 【判断二叉搜索树】Validate Binary Search Tree
- Validate Binary Search Tree 二叉搜索树的合法判断
- 95.Validate Binary Search Tree-验证二叉查找树(中等题)
- 二叉查找树(Binary Search Tree)
- 二叉查找树(Binary Search Tree)
- 98. Validate Binary Search Tree(判断合法二叉搜索树)
- LeetCode 98 Validate Binary Search Tree(判断二叉搜索树)
- IOS基础:retain,copy,assign及autorelease
- android 按两次返回键退出程序
- hdu 1569 and hdu 3657 最小割
- 递归与排序练习(HDOJ习题)--QQ迁移
- leetcode Recover Binary Search Tree
- Validate Binary Search Tree--判断一个树是不是二叉查找树(重重重)
- linux dump/restore
- SVM详解
- mysql常用命令(一)
- android assets文件夹、res/raw、res/layout的区别与联系
- 重载(overload)、覆盖(override)、隐藏(hide)
- (四)概率
- c语言中的冒泡排序简单介绍
- KMP算法 AC自动机