关闭

leetcode 098 Validate Binary Search Tree

95人阅读 评论(0) 收藏 举报
分类:

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.

Subscribe to see which companies asked this question



/**
 * 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 valid(TreeNode* node, TreeNode* &pre) {
		if(node==NULL) return true;
		if(valid(node->left, pre)) {
			if(pre!=NULL && pre->val >= node->val) return false;
			pre=node;
			return valid(node->right, pre);
		}
		return false;
	}
	bool isValidBST(TreeNode* root) {
		if(root == NULL) return true;
		TreeNode *pre=NULL;
		return valid(root, pre);
	}
};




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:118328次
    • 积分:4764
    • 等级:
    • 排名:第6308名
    • 原创:378篇
    • 转载:4篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论