LeetCode98 Validate Binary Search Tree 合法二叉搜索树

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.

Example 1:

Input:
    2
   / \
  1   3
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
             is 5 but its right child's value is 4.

题源:here;完整实现:here

思路:

根据第94题中的两种遍历方式,我们有如下两种实现方案。

1 递归

void helper(TreeNode* root, long long& min, bool& result){
	if (!root) return;
	if (root->left) helper(root->left, min, result);
	if (min >= root->val){
		result = false; return;
	}
	else min = root->val;
	if (root->right) helper(root->right, min, result);
}
bool isValidBST(TreeNode* root) {
	bool result = true; long long min = LLONG_MIN;
	helper(root, min, result);

	return result;
}

2 迭代

bool isValidBST2(TreeNode* root){
	stack<TreeNode*> records;
	long long min = LLONG_MIN;
	while (root || records.size()){
		while (root){
			records.push(root);
			root = root->left;
		}
		root = records.top(); records.pop();
		if (min >= root->val) return false;
		else min = root->val;
		root = root->right;
	}

	return true;
}
两种方式都能较快运行,纪念贴图:


猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/81059525
今日推荐