首页 > 其他 > 详细

[Leetcode]Validate Binary Search Tree

时间:2014-11-27 16:28:55      阅读:369      评论:0      收藏: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.

检查一棵树是不是平衡二叉树。上边列出了BST的性质。开始写了一个递归的方法,结果问题出在了INT_MAX和INT_MIN这两个值上,如果这两个值出现在树中,这个方法就不可行了。

class Solution {
public:
	bool isValidBST(TreeNode *root) {
		return check(root, INT_MAX, INT_MIN);
	}
	bool check(TreeNode *root, int max, int min){
		if (NULL == root) return true;
		if (root->val > min && root->val < max){
			return check(root->left, root->val, min) && check(root->right, max, root->val);
		}
		else return false;
	}
};

在网上翻了好久,发现很多之前AC的代码都是这么写的,说明leetcode有可能更新了test cases,加上了对INT_MAX和INT_MIN的检测,使这些代码没办法再AC了(就像reverse integar那道题一样)。这种思路时间复杂度是O(n),空间复杂度是O(0)。

这样的话,这种思路就行不通了。只能从BST的另一个性质出发,中序遍历这棵树,如果这棵树是BST,那么这个遍历结果正好的升序排列的,这样做空间复杂度也到达了O(n)。

class Solution {
public:
	bool isValidBST(TreeNode *root) {
		vector<int> result;
		inorder(root, result);
		for (int i = 1; i < result.size(); i++){
			if (result[i - 1] >= result[i]) return false;
		}
		return true;
	}
	void inorder(TreeNode *root,vector<int> &result){
		if (!root) return;
		if (root->left) inorder(root->left, result);
		result.push_back(root->val);
		if (root->right) inorder(root->right, result);
	}
};



[Leetcode]Validate Binary Search Tree

原文:http://blog.csdn.net/cr_peace/article/details/41545689

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!