一个人的朝圣 — LeetCode打卡第21天
知识总结
今天继续二叉树, 递归的方法还是有难度的
Leetcode 二叉搜索树的最小绝对差
题目说明
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
代码说明
思路就是: 用一个变量记录上一次遍历的值, pre. 然后依赖二叉搜索树的特性, 中序遍历这棵树.
class Solution {
public int ans = Integer.MAX_VALUE;
public int pre = -1;
public int getMinimumDifference(TreeNode root) {
dfs(root);
return ans;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
if(pre == -1){
pre = root.val;
}else{
ans = Math.min(root.val - pre, ans);
pre = root.val;
}
dfs(root.right);
}
}
Leetcode 501. 二叉搜索树中的众数
题目说明
给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回
假定 BST 满足如下定义:
结点左子树中所含节点的值 小于等于 当前节点的值
结点右子树中所含节点的值 大于等于 当前节点的值
左子树和右子树都是二叉搜索树
代码说明
和上一题的思路类似, 依旧采用中序遍历的方法, 有pre记录上一次遍历的值
public Set<Integer> ans = new HashSet<>();
public int maxFre = 0;
public int curFre = 1;
public int pre = Integer.MIN_VALUE;
public int[] findMode(TreeNode root) {
dfs(root);
int[] result = new int[ans.size()];
int i = 0;
for(int ele : ans){
result[i] = ele;
i++;
}
return result;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
if(root.val == pre){
curFre++;
}else{
pre = root.val;
curFre = 1;
}
if(curFre == maxFre){
ans.add(root.val);
}
if(curFre > maxFre){
ans.clear();
ans.add(root.val);
maxFre = curFre;
}
dfs(root.right);
}
Leetcode 236. 二叉树的最近公共祖先
题目说明
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。
代码说明
思路是这样的, 首先我们得先采用后序遍历, 先处理左子树和右子树, 然后再来判断中间的节点.
处理逻辑是:
如果我中间的节点)为空, 返回空
如果我(中间的节点)等于p, 或等于q则直接返回, 发现了.
这个时候我去看我的儿子们, 看看他们有没有找到p和q, 如果两个子树的返回值都不为空, 说明一个找到p, 一个找到q, 那么我就是最小的公共祖先.
如果有一个为空一个不为空, 我就返回不为空的, 我找到了一个
两个都为空, 说明根本我在这边, 我也返回空
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return dfs(root, p, q);
}
public TreeNode dfs(TreeNode root, TreeNode p, TreeNode q){
if(root == null) return root;
if(root == p || root == q){
return root;
}
TreeNode left = dfs(root.left, p, q);
TreeNode right = dfs(root.right, p, q);
if(left != null && right != null) return root;
if(left != null && right == null) return left;
if(left == null && right != null) return right;
return null;
}
}