LeetCode OJ:Path Sum II(路径和II)

本文介绍了一种方法,通过深度优先搜索(DFS)算法在给定的二叉树中查找所有从根节点到叶子节点的路径,使得路径上的节点值之和等于给定的目标值。详细解释了算法实现过程,并提供了Java和C++版本的代码示例。

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]
]

求路径的和与某一特定的值时候对等即可,简单的dfs,代码如下:

 1 class Solution {
 2 public:
 3     vector<vector<int>> pathSum(TreeNode* root, int sum) {
 4         vector<int> res;
 5         dfs(root, res, sum);
 6         return ret;
 7     }
 8 
 9     void dfs(TreeNode * root, vector<int> res, int left)
10     {
11         if(!root) return;
12         if(!root->left && !root->right && left == root->val){
13             res.push_back(root->val);
14             ret.push_back(res);
15         }
16         if(left <= root->val)
17             return;
18         else{
19             res.push_back(root->val);
20             if(root->left)
21                 dfs(root->left, res, left -= root->val);
22             if(root->right)
23                 dfs(root->right, res, left -= root->val);
24         }
25     }
26 private:
27     vector<vector<int>> ret;
28 };

 java版本代码如下,方法相同,就是java的引用处理起来稍微麻烦点,递归尾部应该pop一下。

 1 public class Solution {
 2     public List<List<Integer>> pathSum(TreeNode root, int sum) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         Stack<Integer> tmp = new Stack<Integer>();
 5            dfs(ret, tmp, root, sum);
 6            return ret;
 7     }
 8 
 9     public void dfs(List<List<Integer>> ret, Stack<Integer> tmp, TreeNode root, int remain){
10         if(root == null) return;
11         tmp.push(root.val);
12         if(root.left == null && root.right == null)
13             if(remain == root.val)
14                 ret.add((Stack<Integer>)tmp.clone());
15         if(root.left != null) dfs(ret, tmp, root.left, remain - root.val);
16         if(root.right != null) dfs(ret, tmp, root.right, remain - root.val);
17         tmp.pop();
19     }
20 }

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4912308.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值