牛客网2016.4.11(两个数相加为sum/计数一个int型的二进制有多少个1/二叉树是否左右对称)

2023-05-13,,

求最小的两个数相加为sum

//求最小的两个数相加为sum
public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
List<Integer> list = new ArrayList<Integer>();
if(array == null || array.length==0){
return (ArrayList<Integer>) list;
} for(int i=0;i<array.length-1;i++){
for(int j=i+1;j<array.length;j++){
if(array[i]+array[j] == sum){
list.add(array[i]);
list.add(array[j]);
break;
}
}
if(list.size()!=0){
break;
}
}
//没找到就返回空集合
return (ArrayList<Integer>) list; }

计数一个int型的二进制有多少个1,难点在负数需要补码存

    public int MoreThan0(int n) {
int cnt = 0;
char []c = Integer.toBinaryString(n).toCharArray();
for (char d : c) {
if(d=='1'){
cnt++;
}
}
return cnt;
}

求一个二叉树是否左右对称

中心处理方法

思路,利用栈队列的特性,进行层比较


import java.util.LinkedList;
import java.util.Stack;
public class Solution {
boolean isSymmetrical(TreeNode pRoot) {
Stack<TreeNode> stack = new Stack<TreeNode>();
Stack<TreeNode> StackSon = new Stack<TreeNode>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
stack.push(pRoot);
queue.offer(pRoot);
TreeNode bt1 = null;
TreeNode bt2 = null;
while(stack.size()!=0 || queue.size()!=0){
while(stack.size()!=0){
//出队和出栈
bt1 = stack.pop();
bt2 = queue.poll();
//比较镜像元素
if(bt1==null || bt2==null){
break;
}
if(bt1.val != bt2.val){ return false;
}
//入队
queue.offer(bt1.right);
queue.offer(bt1.left);
//栈的中转队列
StackSon.push(bt2.right);
StackSon.push(bt2.left);
} while(StackSon.size()!=0){
stack.push(StackSon.pop());
}
}
return true;
}
public static void main(String[] args) {
int a[] = {8,6,6,5,7,7,5};
TreeNode root= new CreatTree().CreatTreeWay(a);
System.out.println(new Solution().isSymmetrical(root));
}
}

按层创建二叉树


import java.util.LinkedList; public class CreatTree {
TreeNode root = null;
public TreeNode CreatTreeWay(int a[]){
if(a==null || a.length==0 ){
return null;
}
if(root == null){
root = new TreeNode(a[0]);
}else{
return root;
}
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.offer(root);
TreeNode node = null;
for (int i = 1; i < a.length && list.size()!=0; i++) {
node = list.poll();
node.left = new TreeNode(a[i]);
list.offer(node.left);
if(i+1<a.length){
node.right = new TreeNode(a[i+1]);
list.offer(node.right);
}
}
return root;
}
public static void main(String[] args) {
int a[] = {8,6,6,5,7,7,5};
new CreatTree().CreatTreeWay(a);
}
}

忘了提供二叉树的结点类了


public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null; public TreeNode(int val) {
this.val = val;
}
}

牛客网2016.4.11(两个数相加为sum/计数一个int型的二进制有多少个1/二叉树是否左右对称)的相关教程结束。

《牛客网2016.4.11(两个数相加为sum/计数一个int型的二进制有多少个1/二叉树是否左右对称).doc》

下载本文的Word格式文档,以方便收藏与打印。