Implement a function to check if a binary tree is a binary search tree.
/* The inorder travel of a BST is strictly increasing. We track the pre node of each node during the recursive process, and compare the two node‘s value to determine whether the tree is BST*/ public class IsBinarySearchTree { boolean stat = true; public boolean isValidBST(TreeNode root) { inorder(root, null); return stat; } private TreeNode inorder(TreeNode node, TreeNode pre) { if(node == null) return pre; else { TreeNode temp = inorder(node.left, pre); if(temp != null && node != temp && node.val <= temp.val) stat = false; temp = inorder(node.right, node); return temp; } } }
CTCI 4.5
时间: 2024-10-08 22:56:03