Leetcode: validata 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 keysLessThe node's key.
- The right subtree of a node contains only nodes with keysGreaterThe node's key.
- Both the left and right Subtrees must also be binary search trees.
Address: https://oj.leetcode.com/problems/validate-binary-search-tree/
Algorithm: In-order traversal to see if the value of the node to be traversed increases progressively. Code:
1 /* * 2 * Definition for Binary Tree 3 * Struct treenode { 4 * Int val; 5 * Treenode * left; 6 * Treenode * right; 7 * Treenode (int x): Val (x), left (null), right (null ){} 8 *}; 9 */ 10 Class Solution { 11 Public : 12 Bool Isvalidbst (treenode * Root ){ 13 If (! Root) Return True ; 14 Stack <treenode *> STK; 15 Treenode * P = Root; 16 While (P ){ 17 STK. Push (P ); 18 P = p-> Left; 19 } 20 Treenode * pre = NULL; 21 P = NULL; 22 While (!STK. Empty ()){ 23 Pre = P; 24 P = STK. Top (); 25 STK. Pop (); 26 If (Pre & P-> Val <= pre-> Val ){ 27 Return False ; 28 } 29 If (P-> Right ){ 30 Treenode * q = p-> Right; 31 While (Q ){ 32 STK. Push (Q ); 33 Q = Q-> Left; 34 } 35 } 36 } 37 Return True ; 38 } 39 };
Leetcode: validata Binary Search Tree