1)一棵二叉树,每个节点都有权值,树的父节点和子节点不能同时选取,遍历二叉树,求节点和最大?(递归思想写算法思想和c语言代码)
2-)删除链表元素值相同的元素并统计新表长度?(c语言代码)
3)用二叉树和三叉树表示 谁占用的存储空间少?(非代码)
现有代码:(不是c语言不合要求)
望采纳
1
public static class Node{
public Node left;
public Node right;
public int val;
public int id;
public Node(int val,int id){
this.val=val;
this.id=id;
this.left=null;
this.right=null;
}
}
public static HashMap<Integer,Node> map;//key为id,value为node
public static int res=0;//保存结果
public static void process(Node head,int xor){//表示以head为头结点的
if(head==null)
return ;
count(head,xor);
process(head.left,xor);
process(head.right,xor);
}
public static void count(Node node,int xor){//从这个节点出发的异或
if(node==null) return ;
int tmp=xor^node.val;
res=Math.max(res, xor);
count(node.left,tmp);
count(node.right,tmp);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
map=new HashMap<>();
while(sc.hasNext()){
int N=sc.nextInt();
sc.nextLine();
int[][] info=new int[N][4];
for(int i=0;i<N;i++){
for(int j=0;j<4;j++){
info[i][j]=sc.nextInt();
}
Node node=new Node(info[i][1],info[i][0]);
map.put(info[i][0], node);
sc.nextLine();
}
Node head=null;
for(int i=0;i<info.length;i++){
int left=info[i][2];
int right=info[i][3];
int id=info[i][0];
Node node=map.get(id);
node.left=left==-1?null:map.get(left);
node.right=right==-1?null:map.get(right);
if(i==0){
head=node;
}
}
process(head,0);
System.out.println(res);
}
}
2
struct ListNode* deleteDuplicates(struct ListNode* head){
struct ListNode* p = head;
if(!head) return NULL;
else{
while(p->next){
if(p->val==p->next->val){
p->next = p->next->next;
}else{
p = p->next;
}
}
return head;
}
}
3 在相同得精度要求下,由于三叉树较二叉树需要得步数更少,
所以它既减少了计算量,又节约了时间
自己动手,丰衣足食
public int rob(TreeNode root) {
if(root == null){
return 0;
}
// 定义一个HashMap 存储每个节点 盗窃的最优解
Map<TreeNode,Integer> result = new HashMap<>();
// 定义一个HashMap 储存每个节点 不盗窃的最优解
Map<TreeNode,Integer> result1 = new HashMap<>();
Stack<TreeNode> stack = new Stack<>();
Stack<TreeNode> stack1 = new Stack<>();
stack.add(root);
stack1.add(root);
while(!stack.isEmpty()){
TreeNode pop = stack.pop();
if(pop.left != null){
stack.add(pop.left);
stack1.add(pop.left);
}
if(pop.right != null){
stack.add(pop.right);
stack1.add(pop.right);
}
}
while(!stack1.isEmpty()){
TreeNode pop = stack1.pop();
// 当 当前节点盗窃的情况下,最优解
// 当前节点盗窃 所以子节点都只能不盗窃 所以 左右节点的不盗窃最优解加上当前节点的值,
result.put(pop,(pop.left == null ? 0:result1.get(pop.left)) + (pop.right == null ? 0:result1.get(pop.right)) + pop.val);
// 当 当前节点不盗窃下的最优解
// 左右的节点都可以是盗窃和不盗窃
int leftMax = 0;
if(pop.left != null){
leftMax = Math.max(result.get(pop.left),result1.get(pop.left));
}
int rightMax = 0;
if(pop.right != null){
rightMax = Math.max(result.get(pop.right),result1.get(pop.right));
}
result1.put(pop,leftMax + rightMax);
}
return Math.max(result.get(root),result1.get(root));
}