【LeetCode】98. Validate Binary Search Tree

题目:

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

Assume a BST is defined as follows:less

  • 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.

提示:

这道题须要知道一个二叉搜索树的特性,就是一个二叉搜索数的中序遍历结果是一个严格单调递增序列。在知道了这个性质以后,就很好解了,这里咱们给出非递归和递归两种解法。函数

代码:

非递归:post

/**
 * 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 isValidBST(TreeNode* root) {
        if (!root) {
            return true;
        }
        inOrder(root);
        for (int i = 1; i < v.size(); ++i) {
            if (v[i] <= v[i-1]) {
                return false;
            }
        }
        return true;
    }
    
    void inOrder(TreeNode* node) {
        if (!node) {
            return;
        }
        inOrder(node->left);
        v.push_back(node->val);
        inOrder(node->right);
    }
    
private:
    vector<int> v;
};

用了一个额外的vector存储中序遍历的结果,看上去好像不是太理想,再看一下递归方法:spa

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

代码简单了不少,其实遍历的时候仍是按照中序的思路来的,可是因为pre指针在函数间传递的过程中指向的位置会发生改变,所以须要注意在函数参数那里须要将其写为指针的引用。指针

相关文章
相关标签/搜索