leetcode之判斷是否BST二分搜尋樹
阿新 • • 發佈:2019-01-23
題目:
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.
思路:一種方法是,先判斷左側左子樹是否為BST,再判斷右子樹是否為BST,如果都是,再判斷左子樹最大的是否小於根節點,右子樹最小的是否大於根節點,如果都是,則為合法的BST,具體實現可用遞迴,可是這種方法的缺陷是遞迴的次數太多,時間複雜度太大。另一種時間複雜度合理的思路是把這這棵樹按照中序遍歷打印出來,看看是否從小到大,因為中序遍歷從小到大等價於為BST,實現按照遞迴來做,遞迴次數合理,時間複雜度不會太大。
程式碼:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct Node { int val; Node * next; Node(int x) : val(x), next(NULL){} }; class Solution { public: Node * makeInorderList(TreeNode * root) { if(root==NULL) { return NULL; } if(root->left==NULL && root->right==NULL) { Node * list= new Node(root->val); return list; } if(root->left!=NULL) { Node * list=makeInorderList(root->left); Node * p=list; while(p->next!=NULL) { p=p->next; } p->next=new Node(root->val); if(root->right!=NULL) { p=p->next; p->next=makeInorderList(root->right); } return list; }else { Node * list=new Node(root->val); if(root->right!=NULL) { list->next=makeInorderList(root->right); } return list; } } bool isValidBST(TreeNode *root) { if(root==NULL) { return true; } Node * list=makeInorderList(root); Node * p=list; if(p->next==NULL) { return true; } Node *q=p->next; while(q!=NULL) { if(p->val>=q->val) { return false; } p=p->next; q=q->next; } return true; } };