您的位置:首页 > 其它

LeetCode之“树”:Validate Binary Search Tree

2015-07-08 19:59 381 查看
  题目链接

  题目要求:

  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:

1
/ \
2   3
/
4
\
5

  The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.

  用惯性思维(即判断某节点的值与其左右子节点的值得关系)去解决这道题,相对麻烦些(花了比较多的时间,最后还是很难兼顾各种情况)。我们可以用中序遍历的方法将整棵树输出,然后再判断输出序列是否是递增序列就行了。

  还有一篇博文的想法特别好,我们要将关注点放在节点本身,然后不断更新它的上下限。

  具体程序如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValidBSTSub(root, LONG_MIN, LONG_MAX);
}

bool isValidBSTSub(TreeNode *tree, long alpha, long beta)
{
if(!tree)
return true;

if(tree->val > alpha && tree->val < beta)
return isValidBSTSub(tree->left, alpha, tree->val) &&
isValidBSTSub(tree->right, tree->val, beta);
else
return false;
}
};


  上边程序用到了LONG_MIN、LONG_MAX,主要是为了应付比较极端的测试集。下图是C/C++中个数据类型的最大值宏定义列表:

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