您的位置:首页 > 编程语言 > C语言/C++

[Leetcode 98] Validate Binary Search Tree

2016-01-13 18:03 471 查看
原题:

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?

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}”.

这道题意思就是判断一棵树是否为二叉搜索树,关于二叉搜索树的定义,维基百科百度百科都给出了很清晰的描述,这里就不赘述。

我的做法很简单,借助于一个栈,把整棵二叉树放进一个列表里,最后检查列表里面的元素是否递增就可以了。递增的话就满足二叉搜索树。

那这道题主要的点就是放的方法了,在这里,先将根节点入栈,再检测左子节点,如果有,就处理左子节点,没有的话就弹出根节点,放入列表中,再放右子节点。

这边主要就是因为左子节点一定比父节点小,右子节点一定比父节点大。用一副图来表示会比较清楚:

2
/ \
1   6
/
3
\
4


举例因素,这就是一颗二叉搜索树,基本特征就是左子树上面的元素一定比父节点小,右边的一定比父节点大。

root节点为2,首先当前节点为2,2先入栈,再查找左子树,为1,1再入栈,再查找1的左子树,为空,因为这时候栈不空,所以出栈,栈顶为1,所以1出来,放到列表中,当前节点转移到1的右子树上(依旧为空),因为栈还是不空,所以继续出栈,2又出来,2放入列表,当前节点转移到2的右子树上,是6,把6再压入栈,再对剩下的做前面的处理。代码实现如下:

/**
* 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) {
if(!root) return true;
TreeNode *current = root;
stack<TreeNode *> s;
vector<int> v;
while(current||!s.empty())
{
if(current!=NULL)
{
s.push(current);
current = current->left;
}else
{
current = s.top();
s.pop();
v.push_back(current->val);
current = current->right;
}

}
for(size_t i=0;i!=v.size()-1;++i)
{
if(v[i]>=v[i+1])
return false;
}
return true;

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