题目:
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
方法一:
-
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ /* 1.通过递归来排序,中序遍历 2.在递归时将其放入栈中 3.遍历栈,是否有出现不满足情况,或者出现元素重复的情况 */ class Solution { private Stack<Integer> stack; public boolean isValidBST(TreeNode root) { if(root == null) return true; stack = new Stack<>(); inOrder(root);//中序遍历之后得到单调递增的序列,栈顶为最大的元素 int i = stack.pop();//栈顶为最大的元素 int j ; while(!stack.isEmpty()){ j = stack.pop(); if(i <= j){//前一个小于后一个即出错 return false; } i = j; } return true; } public void inOrder(TreeNode root){//中序遍历 if(root != null){ inOrder(root.left); stack.push(root.val); inOrder(root.right); } } }
方法二:
-
class Solution { public boolean isValidBST(TreeNode root) { if(root == null) return true; List<Integer> list = new ArrayList<Integer>();//用于存放结果集 inOrder(root,list); for(int i = 1;i <= list.size() - 1;i++){ if(list.get(i - 1) >= list.get(i)){//前一个大于后一个,错误 return false; } } return true; } public void inOrder(TreeNode root,List<Integer> list){//中序遍历获得递升顺序 if(root != null){ inOrder(root.left,list); list.add(root.val); inOrder(root.right,list); } } }