LeetCode:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
1.思路
创建可变的临时指针,采用递归方法中序遍历对
2.代码实现
// 中序遍历,将树上结果加入数组,对数组进行遍历,获取相邻元素之差的最小值
class Solution {
List<Integer> list = new ArrayList<>();
public void traversal(TreeNode root) {
if (root == null) return;
traversal(root.left);
list.add(root.val);
traversal(root.right);
}
public int getMinimumDifference(TreeNode root) {
traversal(root);
if (list.size() < 2) return 0;
int result = Integer.MAX_VALUE;
for (int i = 1; i < list.size(); i++) {
result = Math.min(result, list.get(i) - list.get(i - 1));
}
return result;
}
}
// 递归方法
class Solution {
TreeNode pre;
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
if (root == null) return 0;
traversal(root);
return result;
}
void traversal(TreeNode root) {
if (root == null) {
return;
}
// 左
traversal(root.left);
// 中
if (pre != null) {
result = Math.min(result, root.val - pre.val);
}
pre = root;
// 右
traversal(root.right);
}
}
3.复杂度分析
时间复杂度:O().
空间复杂度:O().
LeetCode:501. 二叉搜索树中的众数 - 力扣(LeetCode)
1.思路
中序遍历,借用双指针法 + 递归法,将出现次数的最大值加入结果中,遍历过程进行覆盖操作
2.代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
ArrayList<Integer> resList;
int maxCount;
int count;
TreeNode pre; // 前驱节点
public int[] findMode(TreeNode root) {
resList = new ArrayList<>();
maxCount = 0;
count = 0;
pre = null;
findMode1(root);
int[] res = new int[resList.size()];
for (int i = 0; i < resList.size(); i++) {
res[i] = resList.get(i);
}
return res;
}
public void findMode1(TreeNode root) {
if (root == null) {
return;
}
// 左
findMode1(root.left);
// 中
int rootValue = root.val;
// 计数
if (pre == null || rootValue != pre.val) {
count = 1;
} else {
count++;
}
// 更新结果及maxCount
if (count > maxCount) {
resList.clear();
resList.add(rootValue);
maxCount = count;
} else if (count == maxCount) {
resList.add(rootValue);
}
pre = root;
findMode1(root.right);
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).
LeetCode:236. 二叉树的最近公共祖先 - 力扣(LeetCode)
1.思路
破题的关键,从下向上遍历,也即借助递归方法的回溯,只要遇到节点==p或q中的一个直接返回即可。
2.代码实现
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 right;
} else if (left != null && right == null) {
return left;
} else {
return root;
}
}
}
3.复杂度分析
时间复杂度:O(n).
空间复杂度:O(n).