[LeetCode 題解]: Validate Binary Search Tree

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   strong   io   for   

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.

 

confused what "{1,#,2,3}" means? 


OJ‘s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.

Here‘s an example:

   1  /  2   3    /   4         5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". 題意:給定一顆二叉樹,判斷該樹是否是二叉排序樹。二叉排序樹的規定:(1)如果存在左子樹,則左子樹的所有節點的值都要小於根節點的值。(2)如果存在右子樹,則右子樹的所有節點的值都要大於根節點的值。(3)如果一棵以root為根節點的樹是二叉排序樹,那麼其左子樹和右子樹也必須是二叉排序樹。 先給出我想到的解:在之前有寫到過用隊列建立一顆二叉排序樹,其過程類似於二叉樹的中序遍曆。因此,可以反過來看出二叉排序樹的中序遍曆的結果組成的序列應該是有序的。根據這種想法,可以得到如下代碼:
class Solution {public:    bool isValidBST(TreeNode *root) {        if(!root ||(!root->left && !root->right)) return true;         vector<int> vi;         vi.clear();         // 用非遞迴的方式對樹進行中序遍曆,將結果存放到vi數組中         stack<TreeNode* > s;         TreeNode *tmp=root;         while(!s.empty() || tmp){            if(tmp){                s.push(tmp);                tmp = tmp->left;            }else{                tmp = s.top();                s.pop();                vi.push_back(tmp->val);                tmp = tmp->right;            }         }         //對中序遍曆的結果進行判斷,注意不能有重複的數字         for(int i=1;i<vi.size();i++){            if(vi[i]<=vi[i-1]) return false;         }         return true;    }};

轉載請註明出處: http://www.cnblogs.com/double-win/ 謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.