利用二叉搜索树的特性
二叉搜索树采用中序遍历,其实就是一个有序数组
Integer.MAX_VALUE
Integer.MIN_VALUE
中序遍历
class Solution {
TreeNode node = null;
int Min = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
inOrder(root);
return Min;
}
private void inOrder(TreeNode root){
if(root == null){
return;
}
// 左
inOrder(root.left);
//中
if(node != null){
int diff = Math.abs(root.val - node.val);
if(diff < Min){
Min = diff;
}
}
node = root;
//右
inOrder(root.right);
}
}
普通的二叉树 怎么求众数
一些方法的回顾
Integer.MIN_VALUE Integer.MAX_VALUE
map.values(); // 获取到所有的value
map.entrySet(); 返回 Map.Entry<> 的集合
entry.getKey();
emtry.getValue();
map.getOrDefault();
class Solution {
Map<Integer, Integer> map = null;
public int[] findMode(TreeNode root) {
map = new HashMap<>();
inOrder(root);
int max = Integer.MIN_VALUE;
for(Integer val : map.values()){
if(val > max){
max = val;
}
}
List<Integer> res = new ArrayList<>();
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
if(entry.getValue() == max){
res.add(entry.getKey());
}
}
int size = res.size();
int[] ans = new int[size];
for(int i = 0; i < size; i++){
ans[i] = res.get(i);
}
return ans;
}
private void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
map.put(root.val, map.getOrDefault(root.val, 0) + 1);
inOrder(root.right);
}
}
利用二叉搜索树的特性
用一个pre节点 在二叉树遍历的过程中不断记录前一个节点
来判断是否相等 并记录次数
class Solution {
List<Integer> list;
TreeNode pre;
int count;
int maxcount;
public int[] findMode(TreeNode root) {
list = new ArrayList<>();
maxcount = 0;
pre = null;
count = 0;
inOrder(root);
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); i++){
res[i] = list.get(i);
}
return res;
}
private void inOrder(TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
if(pre == null || root.val != pre.val){
count = 1;
}else{
count++;
}
if(count == maxcount){
list.add(root.val);
}
if(count > maxcount){
list.clear();
list.add(root.val);
maxcount = count;
}
pre = root;
inOrder(root.right);
}
}
难题
首先找到公共祖先肯定要自底向上查找 需要用到后序遍历
递归函数需要有返回值 来判断是否找到符合要求的节点
在递归函数有返回值的情况下:如果要搜索一条边,递归函数返回值不为空的时候,立刻返回,如果搜索整个树,直接用一个变量left、right接住返回值,这个left、right后序还有逻辑处理的需要,也就是后序遍历中处理中间节点的逻辑(也是回溯)
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || 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 null;
}else if(left != null && right == null){
return left;
}else if(left == null && right != null){
return right;
}else{
return root;
}
}
}