leetcode 098 Validate Binary Search Tree

原创 2016年05月30日 21:24:15

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);
	}
};




相关文章推荐

LeetCode 098 Validate Binary Search Tree

题目 验证BST 代码1...
  • seawade
  • seawade
  • 2015年04月10日 23:11
  • 220

【LeetCode-面试算法经典-Java实现】【098-Validate Binary Search Tree(验证二叉搜索树)】

【098-Validate Binary Search Tree(验证二叉搜索树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a binary tree,...

LeetCode098 Validate Binary Search Tree

详细见:leetcode.com/problems/validate-binary-search-tree Java Solution: github package leetcode...
  • zxwtry
  • zxwtry
  • 2017年04月25日 21:35
  • 74

098 Validate Binary Search Tree [Leetcode]

题目内容: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST ...

【LeetCode】98. Validate Binary Search Tree 解法,中序遍历,搜索二叉树合法性

98. Validate Binary Search Tree Total Accepted: 90083 Total Submissions: 430775 Difficulty: Med...

【Leetcode】Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined...

leetcode No98. Validate Binary Search Tree

Question: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a...

LeetCode --- 98. Validate Binary Search Tree

题目链接:Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree...
  • makuiyu
  • makuiyu
  • 2015年04月14日 19:51
  • 620

LeetCode - 98. Validate Binary Search Tree

Binary Search Tree有一个非常重要的性质,它的中序遍历是递增的,这是一个充要条件,可以用它来判断Binary Search Tree,时间复杂度为O(n),代码如下: /** ...

LeetCode 98: Validate Binary Search Tree

Validate Binary Search TreeGiven a binary tree, determine if it is a valid binary search tree (BST)....
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 098 Validate Binary Search Tree
举报原因:
原因补充:

(最多只允许输入30个字)