您的位置:首页 > 其它

Validate Binary Search Tree -- LeetCode

2016-01-27 06:36 531 查看
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.

思路:二叉搜索树如果按照in-order traversal来遍历的话,所有节点会按照从小到大的顺序被遍历。


Pre-order

Display the data part of the root (or current node).

Traverse the left subtree by recursively calling the pre-order function.

Traverse the right subtree by recursively calling the pre-order function.

In-order

Traverse the left subtree by recursively calling the in-order function.

Display the data part of the root (or current node).

Traverse the right subtree by recursively calling the in-order function.

In a BST, in-order traversal retrieves data in sorted order.


Post-order

Traverse the left subtree by recursively calling the post-order function.

Traverse the right subtree by recursively calling the post-order function.

Display the data part of the root (or current node).



class Solution {
public:
bool validate(TreeNode* root, TreeNode* &pre)
{
if (root == NULL) return true;
if (!validate(root->left, pre)) return false;
if (pre != NULL && pre->val >= root->val) return false;
pre = root;
return validate(root->right, pre);
}
bool isValidBST(TreeNode* root) {
TreeNode* pre = NULL;
return validate(root, pre);
}
};


代码中,我用了一个全局指针pre来记录in-order traversal过程中的上一个节点。如果上一个节点的值比当前节点的值要大或者相等,则不是BST。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: