1.二叉树的深度
import java.util.Queue;
import java.util.LinkedList;
public class Solution{
public int TreeDepth(TreeNode root){
if(root == null) return 0;
Queue<TreeNode> queue=new LinkedList();
queue.add(root);
int high=0;
int size;
TreeNode node;
while(queue.size!=0){
size=queue.size();
while(size!=0){
node=queue.poll();
if(node.left!=null)
queue.add(node.left);
if(node.left!=null)
queue.add(node.right);
size--;
}
high++;
}
return high;
}
}
思路:层次遍历
1.求最大深度,可用队列。满足先进先出的特性。
a.初始化:一个队列queue<TreeNode>q,将root节点入队列q
b.如果队列不空,做如下操作;
c.弹出队列头,保存为node,将node的左右非空孩子加入队列
d.做2,3步骤,直到队列为空
2.平衡二叉树
public class Solution{
public boolean IsBalanced_Solution(TreeNode root){
return depth(root)!=-1;
}
public int depth(TreeNode root){
if(root==null) return 0;
int left=depth(root.left);
if(left==-1) return -1;
int right=depth(root.right);
if(right==-1) return -1;
if(left-right<(-1)||left-right>1)
return -1;
else
return 1+(left>right?left:right);
}
}
思路:判断一个数是否为平衡二叉树,平衡二叉树的左子树的高度与右子树的高度差的绝对值小于等于1,同样左子树是平衡二叉树,右子树为平衡二叉树。
1.判断左右子树,先判断左子树是不是平衡二叉树,如果不是的话,直接返回-1,如果是的话,在继续判断右子树。
2.判断右子树,右子树如果不是的话,也直接返回-1,是的话,继续判断左右子树的高度相差是否为1.
3.数组中只出现一次的两个数字
import java.util.*;
public class Solution{
public int[] FindNumsAppearOnce(int[] array){
int sum=0;
for(int x:array)
sum^=x;
int index=0;
while((sum>>index&1)==0) index++;
int first=0;
for(int x:array)
if((x>>index&1)==0) first ^=x;
int second=sum^first;
retrun new int[]{first,second};
}
}
思路:(可以用哈希表和异或)
异或特点:两个相同的数异或后为0,一个数和0异或后还是他本身 1^1=0 A^0=A
(1).将数组中所有数字做异或处理
(2).由于相同数字异或结果为0,0与数字x异或的结果为x,所以最终的结果为单独出现的数字的异或结果
1.将数组分为两部分,一部分为first,另外一部分为second
2.找到first的位置
3.在用sum^first:d=a^b^c 可以推出a=d^b^c;