二叉搜索树
本题有一个相对比较简单的方法,可以利用二叉搜索树的特性:其中序遍历是严格单调递增的。
class Solution { List<Integer> list; public boolean isValidBST(TreeNode root) { //利用平衡二叉树的特性 list = new ArrayList<>(); traversal(root); for (int i = 0; i < list.size()-1; i++) { if (list.get(i) >= list.get(i+1)){ return false; } } return true; } public void traversal(TreeNode root) { if (root == null) return ; traversal(root.left); list.add(root.val); traversal(root.right); } }
但其实我们可以在遍历的时候直接判断是否严格递增。
class Solution { TreeNode pre = null;//用第一个节点记录最小值是因为测试数据中有longlong类型的最小值 public boolean isValidBST(TreeNode root) { //中序递归 if(root == null) return true; boolean left = isValidBST(root.left); if(pre != null && pre.val >= root.val) return false; pre = root; boolean right = isValidBST(root.right); return left && right; } }
类似题目
class Solution { List<Integer> list; public int getMinimumDifference(TreeNode root) { list = new ArrayList<>(); traversal(root); int minDiff = Math.abs(list.get(0) - list.get(1)); for (int i = 1; i < list.size() - 1; i++) { int diff = Math.abs(list.get(i) - list.get(i+1)); minDiff = Math.min(diff,minDiff); } return minDiff; } public void traversal(TreeNode root) { if (root == null) return; traversal(root.left); list.add(root.val); traversal(root.right); } }
class Solution { List<Integer> resList; TreeNode pre; int count = 0; int maxCount = 0; public int[] findMode(TreeNode root) { resList = new ArrayList<>(); pre = null; traversal(root); int[] res = new int[resList.size()]; for (int i = 0; i < resList.size(); i++) { res[i] = resList.get(i); } return res; } public void traversal(TreeNode root) { if (root == null) return; traversal(root.left); //计数 //如果两个数不相等(包括首元素的情况) if(pre == null || pre.val != root.val) { count = 1; }else { count++; } //判断是否是最多的 if (count > maxCount){ resList.clear(); resList.add(root.val); maxCount = count; }else if (count == maxCount) { resList.add(root.val); } pre = root; traversal(root.right); } }