501.二叉搜索树中的众数
https://leetcode.cn/problems/find-mode-in-binary-search-tree/description/
/**
* 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> res = new ArrayList<>();
int count = 0 ;
int maxCount = Integer.MIN_VALUE;
TreeNode prev = null;
public int[] findMode(TreeNode root) {
//中序遍历
dfs(root);
int size = res.size();
int[] ans = new int[size];
for(int i = 0; i < size; i++){
ans[i] = res.get(i);
}
return ans;
}
void dfs(TreeNode root){
if(root==null) return;
dfs(root.left);
if(prev!=null && root.val == prev.val){
count++;
}else{
count = 1;
}
if(count==maxCount){
res.add(root.val);
}
if(count>maxCount){
maxCount = count;
res.clear();
res.add(root.val);
}
prev = root;
dfs(root.right);
}
}
36. 二叉树的最近公共祖先
/**
* 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) {
if (root == null)
return null;
if (root == p || root == q)
return root;
// 递归遍历左子树,只要在左子树中找到了p或q,则先找到谁就返回谁
TreeNode left = lowestCommonAncestor(root.left, p, q);
// 递归遍历右子树,只要在右子树中找到了p或q,则先找到谁就返回谁
TreeNode right = lowestCommonAncestor(root.right, p, q);
// 如果在左子树中 p和 q都找不到,则 p和 q一定都在右子树中,右子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
if (left == null)
return right;
// 否则,如果 left不为空,在左子树中有找到节点(p或q),这时候要再判断一下右子树中的情况,如果在右子树中,p和q都找不到,则
// p和q一定都在左子树中,左子树中先遍历到的那个就是最近公共祖先(一个节点也可以是它自己的祖先)
else if (right == null)
return left;
else
return root; // 否则,当 left和 right均不为空时,说明 p、q节点分别在 root异侧, 最近公共祖先即为 root
}
}