合并两个递增链表 && 树的子结构

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;

	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值