1. 合并 两个 递增 链表
import java.util.ArrayList;
import java.util.List;
/**
*
*/
/***
* @author 18071
* @Date 2019年3月7日
* 功能: 合并两个递增链表 ,使其递增
***/
public class test {
public static void main(String args[]) {
Solution s=new Solution();
List<Integer> list1 = new ArrayList();
List<Integer> list2 = new ArrayList();
for(int i=0;i<10;i+=2) {
list1.add(i);
}
for(int i=1;i<10;i+=2) {
list2.add(i);
}
List<Integer> list12= s.getnewlist(list1, list2);
for(int i=0;i<list12.size();i++) {
System.out.println(list12.get(i));
}
}
}
class Solution{
public List<Integer> getnewlist(List<Integer> list1 ,List<Integer> list2) {
List<Integer> newlist = new ArrayList();
int l1= 0;
int l2=0;
if(list1==null||list2 == null) {
return null;
}
while(l1<list1.size()&&l2<list2.size()) {
if(list1.get(l1)<list2.get(l2)) {//
newlist.add(list1.get(l1));
l1++;
}
else if (list1.get(l1)>=list2.get(l2)){
newlist.add(list2.get(l2));
l2++;
}
}
while (l1<list1.size()) {
newlist.add(list1.get(l1));
l1++;
}
while(l2<list2.size() ){
newlist.add(list2.get(l2));
l2++;
}
return newlist;
}
}
2. 树的子结构
本题注意递归思路的应用
第一个find函数 通过 res 来进行 入口点的查找
第二个core函数 是在确定入口点之后,查找左右子节点是否与给定的原树相同
所以返回的是 左右的&&
/**
*
*/
/***
* @author 18071
* @Date 2019年3月7日 功能: 树的子结构
*
***/
public class test {
public static void main(String args[]) {
TreeNode root =new TreeNode (1);
root.right=new TreeNode (2);
root.left=new TreeNode (3);
root.left.left=new TreeNode (1);
TreeNode test =new TreeNode (1);
test.right=new TreeNode (2);
test.left=new TreeNode (3);
Solution s= new Solution ();
if(s.find(root, test)) {
System.out.println("true ");
}
else {
System.out.println("false");
}
}
}
class Solution {
public boolean find(TreeNode root, TreeNode test) {
boolean res= false;
if (root != null && test != null) {//找到入口点
if(root.val==test.val) {
res=core(root,test);
}
if(!res) {
res=find(root.left, test.left);
}
if(!res) {
res=find(root.right, test.right);
}
}
return res;
}
public boolean core(TreeNode root, TreeNode tes) {
if(tes==null) {
return true;
}
if(root ==null )
{
return false;
}
if(root.val!= tes.val) {
return false;
}
return core (root.left,tes.left)
&&
core(root.right,tes.right);
}
}
class TreeNode {
TreeNode left;
TreeNode right;
int val;
TreeNode(int x) {
this.val = x;
}
}
本文探讨了两种核心算法:合并两个递增链表,确保结果链表保持递增顺序;以及检查一棵树是否包含另一棵树的结构,通过递归方法实现。涉及的数据结构包括链表和树,算法关键在于递归思想的应用。
1306

被折叠的 条评论
为什么被折叠?



