【leetcode】【medium】98. Validate Binary Search Tree

98. 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:

    2
   / \
  1   3
Input: [2,1,3]
Output: true

Example 2:

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

題目鏈接:https://leetcode-cn.com/problems/validate-binary-search-tree/

 

法一:遞歸

遞歸的寫法也有多種,除了這裏寫到的可以繼續思考有沒有更優美的寫法。

坑:

1)上下邊界都要記錄,因爲還在節點有左有右,判定邊界有區別。

2)如果把上下邊界初始化爲INT_MAX和INT_MIN,要考慮元素值等於邊界的情況,以及更新後的元素值又等於INT_MAX和INT_MIN的情況。

/**
 * 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) {
        return validate(root, LONG_MAX, LONG_MIN);
    }
    bool validate(TreeNode* root, long high, long low){
        if(!root || (!root->left && !root->right)) return true;
        auto l = root->left, r = root->right;
        int mid = root->val;
        if(l && (l->val>=mid || l->val<=low)) return false;
        if(r && (r->val<=mid || r->val>=high)) return false;
        return validate(l, mid, low) && validate(r, high, mid);
    }
};

 

法二:中序遍歷

將樹中序遍歷輸出,如果輸出的不是嚴格遞增數列,則false。

 

發佈了107 篇原創文章 · 獲贊 2 · 訪問量 3304
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章