[Leetcode]Validate Binary Search Tree,leetcodevalidate

來源:互聯網
上載者:User

[Leetcode]Validate Binary Search Tree,leetcodevalidate

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);}};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.