Java实现求二叉树路径总和

24 篇文章 0 订阅
23 篇文章 0 订阅

标题:Java实现求二叉树路径总和

public class TestPathSum02 {
	/**
	 * 使用广度遍历,
	 * 
	 */
	public boolean pathSum(TreeNode p, int target) {
		if(p == null) {
			return false;
		}
		Queue<TreeNode> q = new LinkedList<>();
		q.offer(p);
		
		while(!q.isEmpty()) {
			int size = q.size();
			for(int i = 0; i < size; i++) {
				TreeNode node = q.poll();
				if(node.left != null) {
					node.left.val += node.val;
					q.offer(node.left);
				}
				if(node.right != null) {
					node.right.val += node.val;
					q.offer(node.right);
				}
				if(node.left == null && node.right == null) {
					if(node.val == target) {
						return true;
					}
				}
			}
		}
		
		return false;
	}
	
	/**
	 * 使用深度遍历,递归
	 */
	public boolean pathSum02(TreeNode p, int target, int sum) {
		if(p == null) {
			return false;
		}else {
			boolean res1 = this.pathSum02(p.left, target, sum + p.val);
			boolean res2 = this.pathSum02(p.right, target, sum + p.val);
			if(p.left == null && p.right == null) {
				if(sum + p.val == target) {
					return true;
				}
			}
			
			if(res1 || res2) {
				return true;
			}
			
			return false;
		}
		
		
		
	}
	
	/**
	 * 初始化一个tree
	 * 类广度遍历
	 * @param a
	 * @return
	 */
	public TreeNode initTree(Integer[] a) {
		if(a == null || a.length == 0) {
			return null;
		}
		
		int t = 0;
		TreeNode p = new TreeNode(a[t]);  //至少有一个元素
		Queue<TreeNode> q = new LinkedList<>();
		q.offer(p);
		
		while(!q.isEmpty()) {
			TreeNode node = q.poll();
			if(t + 1 == a.length) {  //先判断数组中是否还有下一个元素
				return p;
			}else {
				t++;
				if(a[t] == null) {  //若下一个元素为null,则不需要创建新的节点
					node.left = null;
				}else {
					node.left = new TreeNode(a[t]);
					q.offer(node.left);
				}
			}
			if(t + 1 == a.length) {
				return p;
			}else {
				t++;
				if(a[t] != null){  //上面的简写,a[t] == null,不需要再赋值
					node.right = new TreeNode(a[t]);
					q.offer(node.right);
				}
			}
		}
		
		return p;
		
	}
	
	
	
	@Test
	public void test() {
		System.out.println("使用init的");
		//中的方法 initTree(Character[])对于参数(char[])不适用
//		Integer[] a = new Integer[] {1, 2, 3, 4, 5, 9, 10, null, 6, 7, 8, null, null, null, 11};
		Integer[] a = new Integer[] {1, 2};
		
		//初始化TreeNode
		TreeNode p = this.initTree(a);
		
//		System.out.println("使用广度遍历");
//		System.out.println("isTrue:" + this.pathSum(p, 3));//更改了TreeNode
		
		System.out.println("使用递归");
		System.out.println("isTrue:" + this.pathSum02(p, 2, 0));  //测试的时候要将上面的广度遍历注释掉,否则会有问题
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值