您的位置:首页 > 其它

LeetCode(98) Validate Binary Search Tree

2015-10-12 16:00 399 查看

题目

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.

OJ’s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:



分析

一倒判断给定二叉树是否为二叉查找树的题目。

看似一道很简单的题目,愣是让我提交了4次才AC。

都卡在了int数据类型溢出问题上了!!! 每每涉及到INT_MIN和INT_MAX的题目都很是头疼。最终还是改变了策略。

/*

* 需要注意的是,左子树的所有节点都要比根节点小,

* 而非只是其左孩子比其小,右子树同样。

*/

//二叉查找树的一个特点就是其中序遍历结果为一个递增序列,可作为用来判断

这个简单的判断规则,开始竟没想到,败在了递归判断!

关于这道题目,这篇博文总结的很好,博文链接

AC代码

class Solution {
public:
/*
* 需要注意的是,左子树的所有节点都要比根节点小,
* 而非只是其左孩子比其小,右子树同样。
*/
bool isValidBST(TreeNode* root) {
if (!root)
return true;

//二叉查找树的一个特点就是其中序遍历结果为一个递增序列,可作为用来判断
InOrder(root);

int size = ret.size();
for (int i = 0; i < size - 1; ++i)
{
if (ret[i] >= ret[i + 1])
return false;
}//for
return true;
}

//中序遍历二叉查找树
void InOrder(TreeNode *root)
{
if (!root)
return;

InOrder(root->left);
ret.push_back(root->val);
InOrder(root->right);

}

private:
vector<int> ret;
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: