package _06binary_tree.day21._01get_min_dif;
import _06binary_tree.TreeNode;
import java.util.Stack;
public class Solution {
TreeNode pre = null;
int result = Integer.MAX_VALUE;
// 迭代
public int getMinimumDifference2(TreeNode root) {
if(root == null)return 0;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()){
if(cur != null){
stack.push(cur);
cur = cur.left; // 左
}else {
cur = stack.pop();
if(pre != null){
result = Math.min(result,cur.val - pre.val); // 中
}
pre = cur;
cur = cur.right; // 右
}
}
return result;
}
// 递归
public int getMinimumDifference(TreeNode root) {
if(root == null)return 0;
traversal(root);
return result;
}
private void traversal(TreeNode cur) {
if(cur == null)return;
traversal(cur.left); // 左
if(pre != null){
result = Math.min(result,cur.val - pre.val); // 中
}
pre = cur;
traversal(cur.right); // 右
}
}
package _06binary_tree.day21._02find_mode;
import _06binary_tree.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Solution {
int maxCount;
int count;
TreeNode pre;
List<Integer> list;
// 迭代
public int[] findMode2(TreeNode root) {
list = new ArrayList<>();
count = 0;
maxCount = 0;
pre = null;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()){
if(cur != null){
stack.push(cur); // 左
cur = cur.left;
}else {
cur = stack.pop(); // 中
if(pre == null || pre.val != cur.val){
count = 1;
}else {
count++;
}
// 更新maxCount
if(count > maxCount){
maxCount = count;
list.clear();
list.add(root.val);
}else if(count == maxCount){
list.add(root.val);
}
pre = cur;
cur = cur.right; // 右
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
// 递归
public int[] findMode(TreeNode root) {
list = new ArrayList<>();
count = 0;
maxCount = 0;
pre = null;
traverse(root);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
private void traverse(TreeNode root) {
if(root == null)return;
// 左
traverse(root.left);
// 中
if(pre == null || pre.val != root.val){
count = 1;
}else {
count++;
}
// 更新maxCount
if(count > maxCount){
maxCount = count;
list.clear();
list.add(root.val);
}else if(count == maxCount){
list.add(root.val);
}
pre = root;
// 右
traverse(root.right);
}
}
package _06binary_tree.day21._03lowest_common_ancestor;
import _06binary_tree.TreeNode;
public 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 (right != null && left == null)return right;
else return root;
}
}