Title Link: 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 is binary search trees.
Confused what "{1,#,2,3}" means? > read more about how binary tree was serialized on OJ.
OJ ' s Binary Tree serialization:
The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
The requirement of this question is to detect whether the binary tree is a two-fork search tree (BST).
Binary search tree, as the name implies, it is a binary tree, that is, each node under a maximum of 2 child nodes. In order to facilitate the search, the binary search tree is either an empty tree or a two-fork tree with the following properties:
- If the left subtree is not empty, the values of all nodes on the left subtree are smaller than the value of the root node;
- If the right subtree is not empty, the value of all nodes on the right subtree is greater than the value of the root node;
- The left and right sub-trees are also two-fork search trees respectively.
Binary search tree also has a feature is that the middle sequence traversal is strictly incremental, so you can use a feature to check whether a binary tree is a two-fork search tree. The pre-variable is used to record the previous node, then the two-fork tree is sequenced, and the number of the pre node is measured less than the current node.
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {3 Public:4 BOOL Isvalidbst(TreeNode *Root)5 {6 TreeNode *Pre = NULL;7 Inordertraversal(Root, Pre);8 }9 Private:Ten BOOL Inordertraversal(TreeNode *P, TreeNode *&Pre) One { A if(P == NULL) - return true; - the if(!Inordertraversal(P - Left, Pre)) - return false; - - if(Pre != NULL && Pre - Val >= P - Val) + return false; - Pre = P; + A if(!Inordertraversal(P - Right, Pre)) at return false; - - return true; - } - };
Reprint please indicate source: Leetcode---98. Validate Binary Search Tree
Leetcode---98. Validate Binary Search Tree