判断一棵树是不是平衡二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
return depth(root)!=-1;
}
public int depth(TreeNode root){
if(root == null)return 0;
int l=depth(root.left);
int r=depth(root.right);
if(l==-1||r==-1){ //有一个树的自树不平衡则不用递归了
return -1;
}
if(Math.abs(l-r)>1)
return -1;
else
return 1+(l > r?l:r);
}
判断二叉树是否对称
public boolean isSymmetric (TreeNode root) {
// write code here
if(root==null){
return true;
}
return Symmetric(root,root);
}
public boolean Symmetric(TreeNode l,TreeNode r){
if(l==null&&r==null) return true;
if(l==null||r==null) return false;
if(l.val!=r.val) return false;
return Symmetric(l.left,r.right)&&Symmetric(l.right,r.left);
}
二叉树的镜像
操作给定的二叉树,将其变换为源二叉树的镜像。
比如: 源二叉树
8
/
6 10
/ \ /
5 7 9 11
镜像二叉树
8
/
10 6
/ \ /
11 9 7 5
public TreeNode Mirror (TreeNode pRoot) {
// write code here
if(pRoot==null) {
return null;
}
TreeNode p=pRoot.left;
pRoot.left=pRoot.right;
pRoot.right=p;
Mirror(pRoot.left);
Mirror(pRoot.right);
return pRoot;
}
NC126 换钱的最少货币数
给定数组arr,arr中所有的值都为正整数且不重复。每个值代表一种面值的货币,每种面值的货币可以使用任意张,再给定一个aim,代表要找的钱数,求组成aim的最少货币数。
如果无解,请返回-1.
输入:[5,2,3],20返回值:4
输入:[5,2,3],0返回值:0
public int minMoney (int[] arr, int aim) {
// 初始化
table = new int[aim+1];
return dp(arr,aim);
}
// 进行剪枝 , 一般动态规划都要
int[] table ;
/**
* 定义 , 要凑出金额 amount , 至少需要 dp(amount) 个硬币
*
* @param arr
* @param amount 要凑的金额
* @return 硬币数量
*/
public int dp(int[] arr, int amount){
//base case 基本返回操作, 当金额等于的0 时候就不用返回了。
if(amount == 0) return 0;
if(amount < 0) return -1;
// 返回某个金额的最少 金币数
if(table[amount]!=0){
return table[amount];
}
int res = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
//遍历金币数组,每个可能都尝试
int subproblem = dp(arr, amount - arr[i]);
// 无解跳过
if(subproblem == -1){
continue;
}
res = Math.min(subproblem + 1, res);
}
res = res == Integer.MAX_VALUE ? -1 : res;
table[amount] = res;
return res;
}
升序数组转化为平衡搜索二叉树
public TreeNode sortedArrayToBST (int[] num) {
// write code here
return head(num,0,num.length-1);
}
public TreeNode head(int[] arr,int l,int r){
if(l>r) return null;
int min=l+(r-l+1)/2;
TreeNode left=head(arr,l,min-1);
TreeNode right=head(arr,min+1,r);
TreeNode node=new TreeNode(arr[min]);
node.left=left;
node.right=right;
return node;
}
只出现一次的字符
可不看自己写的
public int FirstNotRepeatingChar(String str) {
String[] chars=str.split("");
String string="";
for(int i=0;i<str.length();i++){
string=str.substring(0,i)+str.substring(i+1,str.length()); //切掉当前字符
if(!string.contains(chars[i])){
return str.indexOf(chars[i]);
}
}
return -1;