public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(){};
TreeNode(int val,TreeNode left,TreeNode right){
this.val=val;
this.left=left;
this.right=right;
}
TreeNode(int val){
this.val=val;
}
}
class Solution {
int result=Integer.MAX_VALUE;
TreeNode pre;//默认为null
public int getMinimumDifference(TreeNode root) {
if(root==null)return 0;
traversal(root);
return result;
}
public void traversal(TreeNode root){
//中序遍历 左中右
//终止条件
if(root==null)return;
traversal(root.left);//左
//中
if(pre!=null){
// result=Math.min(Math.abs(root.val-pre.val),result);//不用绝对值,前-后一定递增
result=Math.min(root.val-pre.val,result);
}
pre=root;
traversal(root.right);
}
}
/**
* 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 {
int result=Integer.MAX_VALUE;
TreeNode pre;//默认为null
Stack<TreeNode> stack = new Stack<>();
public int getMinimumDifference(TreeNode root) {
if(root!=null){
stack.push(root);
}
while(!stack.isEmpty()){
TreeNode cur=stack.peek();
if(cur!=null){
stack.pop();
if(cur.right != null)//右
stack.add(cur.right);
stack.add(cur);//中
stack.add(null);
if(cur.left != null)//左
stack.add(cur.left);
}else{
stack.pop();
cur=stack.pop();
if(pre!=null)
result=Math.min(cur.val-pre.val,result);
pre=cur;
}
}
return result;
}
}
class Solution {
int count;
ArrayList<Integer> resList;
int maxcount;
TreeNode pre;
public int[] findMode(TreeNode root) {
count=1;
maxcount=Integer.MIN_VALUE;
resList=new ArrayList<>();
search(root);
int n=resList.size();
int[] res=new int[n];
for(int i=0;i<n;i++){
res[i]=resList.get(i);
}
return res;
}
public void search(TreeNode root) {
if(root==null)return;
search(root.left);
if(pre!=null){
if(pre.val==root.val){
count++;
}else{
count=1;
}
}
pre=root;
if(count==maxcount){
resList.add(root.val);
}
if(count>maxcount){
maxcount=count;
resList.clear();
resList.add(root.val);
}
search(root.right);
}
如图:
/**
* 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||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 root;
}
else if(left==null&&right!=null){
return right;
}else if(left!=null&&right==null){
return left;
}else{
return null;
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容