路径总和 II

路径总和 II

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

			  5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

代码与思路

cpp代码1

提交代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
    	vector<vector<int> > result;//记录所有满足条件的路径
    	vector<int> path;//当前的路径
    	int path_value = 0;//当前的路径和
    	preorder(root, path_value, sum, path, result);
    	return result;        
    }

private:
	void preorder(TreeNode *node, int &path_value, int sum,
				vector<int> &path,
				vector<vector<int> > &result){
		if (!node){
			return;
		}
		path_value += node->val;
		path.push_back(node->val);
		if (!node->left && !node->right && path_value == sum){
			result.push_back(path);
		}
		preorder(node->left, path_value, sum, path, result);
		preorder(node->right, path_value, sum, path, result);
		path_value -= node->val;
		path.pop_back();
	}

};

测试代码

#include <stdio.h>

#include <vector>
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    std::vector<std::vector<int> > pathSum(TreeNode* root, int sum) {
    	std::vector<std::vector<int> > result;//记录所有满足条件的路径
    	std::vector<int> path;//当前的路径
    	int path_value = 0;//当前的路径和
    	preorder(root, path_value, sum, path, result);
    	return result;
    }
private:
	void preorder(TreeNode *node, int &path_value, int sum,
				std::vector<int> &path,
				std::vector<std::vector<int> > &result){
		if (!node){
			return;
		}
		path_value += node->val;
		path.push_back(node->val);
		if (!node->left && !node->right && path_value == sum){
			result.push_back(path);
		}
		preorder(node->left, path_value, sum, path, result);
		preorder(node->right, path_value, sum, path, result);
		path_value -= node->val;
		path.pop_back();
	}
};

int main(){
	TreeNode a(5);
	TreeNode b(4);
	TreeNode c(8);
	TreeNode d(11);
	TreeNode e(13);
	TreeNode f(4);
	TreeNode g(7);
	TreeNode h(2);
	TreeNode x(5);
	TreeNode y(1);
	a.left = &b;
	a.right = &c;
	b.left = &d;
	c.left = &e;
	c.right = &f;
	d.left = &g;
	d.right = &h;
	f.left = &x;
	f.right = &y;
	Solution solve;
	std::vector<std::vector<int> > result = solve.pathSum(&a, 22);
	for (int i = 0; i < result.size(); i++){
		for (int j = 0; j < result[i].size(); j++){
			printf("[%d]", result[i][j]);
		}
		printf("\n");
	}
	return 0;
}

java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    List<List<Integer>> result = new LinkedList();
    Stack<Integer> path = new Stack();
    
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        dfs(root, sum);
        return result;
    }
    
    public void dfs(TreeNode root, int sum){
        if(root == null) return;
        if(root.left == null && root.right == null){
            path.push(root.val);
            if(root.val == sum){
                result.add(new ArrayList(path));
            }
            path.pop();
            return;
        }
        
        path.push(root.val);
        if(root.left != null) dfs(root.left, sum - root.val);
        if(root.right != null) dfs(root.right, sum - root.val);
        path.pop();
    }
}

预备知识–先序遍历

/*class BiTree {
    int value;
    BiTree lchild;
    BiTree rchild;
     
    public BiTree() {}
 
    public BiTree(int value) {
        super();
        this.value = value;
    }
}*/
 
/**
* 非递归
* @param b
*/
public static void preScan(BiTree b) {
    int length = 0;
    BiTree[] stack = new BiTree[20];
    stack[length ++] = b;
    BiTree temp;
 
    while(length > 0) {
        temp = stack[-- length];
        System.out.print(temp.value + " ");
         
        if(temp.rchild != null) {
            stack[length ++] = temp.rchild;
        }
        if(temp.lchild != null) {
            stack[length ++] = temp.lchild;
        }
    }
}
     
/**
* 递归
* @param b
*/
public static void scan(BiTree b) {
    if(b != null) {
        System.out.print(b.value + " ");
    }
    if(b.lchild != null) scan(b.lchild);
    if(b.rchild != null) scan(b.rchild);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 您好,这是一个简单的Java路径总和算法。只需要把给定路径中的数字相加即可: public int pathSum(int[] path) { int sum = 0; for (int i = 0; i < path.length; i++) { sum += path[i]; } return sum; } ### 回答2: 当Java中的路径总和算法是一种用于查找从根节点到叶节点的路径上所有节点值之和等于给定目标值的算法。以下是一个简单的Java代码示例: ```java // 树节点定义 class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } public class PathSum { public static boolean hasPathSum(TreeNode root, int targetSum) { if (root == null) { return false; // 如果根节点为空,直接返回false } if (root.left == null && root.right == null && root.val == targetSum) { return true; // 如果是叶节点且节点值等于目标值,返回true } // 递归遍历左子树和右子树 return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val); } public static void main(String[] args) { // 创建一个二叉树 TreeNode root = new TreeNode(5); root.left = new TreeNode(4); root.right = new TreeNode(8); root.left.left = new TreeNode(11); root.left.left.left = new TreeNode(7); root.left.left.right = new TreeNode(2); root.right.left = new TreeNode(13); root.right.right = new TreeNode(4); root.right.right.right = new TreeNode(1); int targetSum = 22; boolean hasPath = hasPathSum(root, targetSum); System.out.println("是否存在路径的节点和等于目标值:" + hasPath); } } ``` 以上代码中,首先定义了一个TreeNode类来表示二叉树的节点,其中包含节点的值以及左右子节点。然后,定义了PathSum类来实现路径总和的算法。在该类中,使用递归的方式遍历二叉树,如果节点为空,则返回false;如果是叶节点且节点值等于目标值,则返回true;否则,递归遍历左子树和右子树,将目标值减去当前节点的值。 在main方法中,创建了一个二叉树,并设置目标值为22,然后调用hasPathSum方法来检查是否存在路径的节点和等于目标值。最后,输出结果显示是否存在这样的路径。 ### 回答3: 当你说路径总和算法时,我理解为在一个二叉树中查找是否存在一条从根节点到叶子节点的路径,使得路径上所有节点值的和等于给定的目标值。以下是一个基于深度优先搜索(DFS)的Java实现: ```java // 定义二叉树节点 class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } public class PathSum { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null && sum - root.val == 0) { return true; // 找到满足条件的路径 } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } public static void main(String[] args) { // 构建二叉树 TreeNode root = new TreeNode(5); root.left = new TreeNode(4); root.right = new TreeNode(8); root.left.left = new TreeNode(11); root.left.left.left = new TreeNode(7); root.left.left.right = new TreeNode(2); root.right.left = new TreeNode(13); root.right.right = new TreeNode(4); root.right.right.right = new TreeNode(1); int targetSum = 22; PathSum pathSum = new PathSum(); boolean hasSum = pathSum.hasPathSum(root, targetSum); System.out.println("是否存在路径和为" + targetSum + "的路径?" + hasSum); } } ``` 以上的代码实现了一个二叉树路径总和算法。首先,在`hasPathSum`方法中,我们根据是否为叶子节点和路径和是否等于给定的目标值进行判断。如果同时满足这两个条件,即找到了一条满足路径总和路径。接着,递归调用方法,在左右子树中寻找新的路径总和。最后,在`main`方法中,我们构建了一个示例二叉树,并调用`hasPathSum`方法进行计算。输出将显示是否存在路径和为目标值的路径。 希望上述解答能对你有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值