算法分析與設計——LeetCode Problem.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
Binary tree [2,1,3], return true.

Example 2:

    1
   / \
  2   3
Binary tree [1,2,3], return false.


解題思路


要判斷二叉樹是否爲二分查找樹只需要將其中序遍歷一遍,並將元素依次保存到數組中,看元素是否升序排列即可,注意元素之間不能相等。

代碼如下

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


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