leetcode解题之112 & 113 & 437. Path Sum java版(二叉树路径和)

这篇博客介绍了如何使用Java解决LeetCode上的三个问题:112. Path Sum、113. Path Sum II 和 437. Path Sum III。对于每个问题,作者提供了问题概述,并讨论了满足特定路径和的根到叶路径的查找方法。解决方案包括自顶向下遍历的策略,以及层次遍历和深度优先搜索的结合。
摘要由CSDN通过智能技术生成

112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

public boolean hasPathSum(TreeNode root, int sum) {
		if (root == null)
			return false;
		return pathCore(root, sum);

	}
	private boolean pathCore(TreeNode root, int sum) {
		if (root != null) {
			if (sum - root.val == 0 && 
					root.left == null && root.right == null)
				return true;
			return pathCore(root.left, sum - root.val) 
					|| pathCore(root.right, sum - root.val);
		}
		return false;
	}

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
给定二叉树求所有的路径,等于指定的和

public List<List<Integer>> pathSum(TreeNode root, int sum) {
		List<List<Integer>> ret = new ArrayList<>();
		if (root == null)
			return ret;
		List<Integer> tmp = new ArrayList<>();
		pathCore(root, ret, tmp, sum);
		return ret;
	}

	// DFS+回溯
	private void pathCore(TreeNode root, List<List<Integer>> ret, List<Integer> tmp, int sum) {
		if (root != null) {
			if (sum - root.val == 0 && root.left == null && root.right == null) {
				tmp.add(root.val);
				ret.add(new ArrayList<>(tmp));
				tmp.remove(tmp.size() - 1);
				return;
			}
			tmp.add(root.val);
			pathCore(root.left, ret, tmp, sum - root.val);
			pathCore(root.right, ret, tmp, sum - root.val);
			tmp.remove(tmp.size() - 1);
		}

	}

437. Path Sum III

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards(traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

先从头结点开始遍历,求得满足条件的路径的个数后,再分别遍历其左右子树,求得满足条件的路径再累加。

用队列层次遍历树的每个节点,再从每个节点开始dfs求出满足条件的路径,将所有的累加就得到结果。

private int count = 0;
	// 如果sum为3,有多条路径1,1,1,那么这属于不同的结果
	public int pathSum(TreeNode root, int sum) {
		if (root == null)
			return 0;
		// 层次遍历每个结点,每个结点调用函数pathSumCore
		Queue<TreeNode> q = new LinkedList<>();
		q.offer(root);
		while (!q.isEmpty()) {
			TreeNode node = q.poll();
			pathSumCore(node, sum);
			if (node.left != null)
				q.offer(node.left);
			if (node.right != null)
				q.offer(node.right);
		}
		return count;
	}

	private void pathSumCore(TreeNode root, int sum) {
		if (root != null) {
			if (sum - root.val == 0) {
				count++;
				// 因为后续有可能出现相加等于0的情况,不需要return
				// return;
			}
			pathSumCore(root.left, sum - root.val);
			pathSumCore(root.right, sum - root.val);
		}
	}
网上版本:

public int pathSum(TreeNode root, int sum) {
		if (root == null)
			return 0;
		//return dfs(root, sum) + pathSum1(root.left, sum) + pathSum1(root.right, sum);
		return dfsCore(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
	}
	private int dfsCore(TreeNode root, int sum) {
		int res = 0;
		if (root == null)
			return res;
		if (root.val == sum)
			res++;
		res+=dfsCore(root.left, sum - root.val);
		res+=dfsCore(root.right, sum - root.val);
		return res;

	}
第二种dfs

private int dfs(TreeNode root, int sum) {
		if (root == null)
			return 0;
		if (sum == root.val)
			return 1 + dfs(root.left, 0) 
			+ dfs(root.right, 0);
		return dfs(root.left, sum - root.val) 
				+ dfs(root.right, sum - root.val);
	}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值