1. 程式人生 > >Leetcode:98.驗證二叉搜尋樹

Leetcode:98.驗證二叉搜尋樹

給定一個二叉樹,判斷其是否是一個有效的二叉搜尋樹。

假設一個二叉搜尋樹具有如下特徵:

  • 節點的左子樹只包含小於當前節點的數。
  • 節點的右子樹只包含大於當前節點的數。
  • 所有左子樹和右子樹自身必須也是二叉搜尋樹。

示例 1:

輸入:
    2
   / \
  1   3
輸出: true

示例 2:

輸入:
    5
   / \
  1   4
     / \
    3   6
輸出: false
解釋: 輸入為: [5,1,4,null,null,3,6]。
     根節點的值為 5 ,但是其右子節點值為 4 。

解題思路:

二叉搜尋樹:中序遍歷中沒有逆序對,且無重複元素。本題的解題思路還是利用中序遍歷,檢查逆序對是否存在。

注意事項:

1.空的樹是二叉搜尋樹,因為沒有逆序對,且無重複元素。(一開始還以為不是~.~)

2.注意不能有重複元素。

3.一旦發現逆序對,則可以停止搜尋。

                         

C++程式碼
#define hasLChild(x) (!(x->left==NULL))
#define hasRChild(x) (!(x->right==NULL))
class Solution {
 public:
     bool isValidBST(TreeNode* root) {
         if (root == NULL) return true;
         In_order_traversal(root);
         return sgn;
     }
     void In_order_traversal(TreeNode* root) {
         if (sgn == false) return;
         if (hasLChild(root)) In_order_traversal(root->left);
         if (temp == NULL) temp = root;
         else {
             if (temp->val >= root->val) {//出現了逆序對
                 sgn = false;
             }
             temp = root;
         }
         if (hasRChild(root)) In_order_traversal(root->right);
     }
 private:
     bool sgn = true;
     TreeNode* temp;
 };