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.
思路:
dfs
我的代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public boolean isValidBST(TreeNode root) { if(root == null) return true; return helper(root, null, null); } public boolean helper(TreeNode root, Integer min, Integer max) { if(root == null) return true; Integer val = root.val; if(min != null && val.compareTo(min) <= 0) return false; if(max != null && val.compareTo(max) >= 0) return false; return helper(root.left, min, root.val) && helper(root.right, root.val, max); } }
学习之处:
- 在helper传入参数的时候,此处只能用Integer对象不能用int,因为int需要初始化,如果min初始化为Integer.MIN_VALUE max初始化为Integer.MAX_VALUE不能排除root.val真的等于Integer.MIN_VALUE max或Integer.MAX_VALUE的corcase
- 之前一直觉得Integer对象的存在没有太多的意义,这道题给了一个很好的应用,既然第一次不能初始化,那么我用Integer中的null正好可以代替第一次,真的是好机智啊!!
- 该问题还可以用中序遍历解决,因为中序遍历要求是递增的顺序的,想想中序遍历的非递归解法,貌似有印象while(stack.isEmpty()||cur !=null),只是在那边再加一个pre就OK了。