一、二叉搜索树中的搜索
利用二叉搜索树的性质,如果val小于root.val,搜索左子树,如果val大于root.val,搜索右子树。
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null || root.val == val) {
return root;
}
if (val < root.val) {
return searchBST(root.left, val);
} else {
return searchBST(root.right, val);
}
}
}
二、验证二叉搜索树
第一种方法,中序遍历二叉树为一个数组,如果数组是递增的,则其为二叉搜索树。
第二种方法用递归和双指针法,双指针法要一个全局变量pre,用来记录当前节点的前一个节点,用来比较。从左子树回溯到当前节点时,那就是用左孩子和当前root比较,然后pre被root赋值,又用于和右孩子比较。
class Solution {
TreeNode pre;
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;
}
}
三、二叉搜索树的最小绝对差
首先它是一个二叉搜索树,中序遍历为数组后,节点最小绝对差一定是数组某对相邻元素的差值。
和上一题一样,需要一个pre指针用来记录前一个节点,在中序遍历下,pre和cur就是递增数组中的相邻两个元素。
class Solution {
TreeNode pre;
int res = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
traversal(root);
return res;
}
public void traversal(TreeNode root) {
if (root == null) return;
traversal(root.left);
if (pre != null) res = Math.min(res, root.val-pre.val);
pre = root;
traversal(root.right);
}
}
四、二叉搜索树中的众数
二叉搜索树按中序遍历形成有序数组后,通过比较相邻元素就可以得到出现频率最高的元素。
通常来说先遍历一遍数组,找出最大频率(maxCount),然后再重新遍历一遍数组把出现频率为maxCount的元素放进集合。其实还有一种方法可以只遍历一次数组。
class Solution {
ArrayList<Integer> res;
int maxCount;
int count;
TreeNode pre;
public int[] findMode(TreeNode root) {
res = new ArrayList<>();
maxCount = 0;
count = 0;
pre = null;
recursion(root);
return res.stream().mapToInt(Integer::intValue).toArray();
}
public void recursion(TreeNode root) {
if (root == null) return;
recursion(root.left);
if (pre == null || pre.val != root.val) {
count = 1;
} else {
count++;
}
if (count == maxCount) res.add(root.val);
if (count > maxCount) {
res.clear();
res.add(root.val);
maxCount = count;
}
pre = root;
recursion(root.right);
}
}
五、二叉树的最近公共祖先
要是可以自底向上查找就好了,这样就可以找到公共祖先了。后续遍历可以用到回溯,将某个值一直向上传递。
递归时如果遇到p或q就返回p或q,如果没遇到就返回null,如果只有一边的子树返回了非null,就返回这一边子树的节点,如果两边的子树都返回了非null,证明我们找到了最近的公共祖先,返回root。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root;
} else if (left == null && right != null) {
return right;
} else if (left != null && right == null) {
return left;
} else {
return null;
}
}
}