[剑指offer]24、二叉树中和为某一值的路径

题目描述

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

分析:

1、因为要包含所有可能的路径,因此返回的结果res为二维数组,用一维数组path保存满足条件的单条路径的结点值

2、从根节点开始,若当前结点为null,直接返回res

3、若当前结点为叶子结点,且结点的值正好和目标值相等,则将该单条路径的结点值数组path加入res

4、将目标值target减去当前结点的值val作为下一个节点的目标值,再分别将当前结点的左节点和右结点分别作为根节点递归求解

5、若当前结点的左右子节点都为空,则回退到上一个结点,即去除path的最后一个值,继续判断

Java代码:

public class Solution {
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> path = new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        if(root == null)
            return res;
        path.add(root.val);
        boolean flag = (root.left == null) && (root.right == null);
        if((root.val == target) && flag)
            res.add(new ArrayList<Integer>(path));
        FindPath(root.left, target-root.val);
        FindPath(root.right, target-root.val);
        if(path.size() != 0)
            path.remove(path.size()-1);
        return res;
    }
}

C++代码:

class Solution {
public:
    vector<vector<int> > res;
    vector<int> path;
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root == NULL)
            return res;
        path.push_back(root->val);
        bool flag = (root->left == NULL && root->right == NULL);
        if((expectNumber == root->val) && flag)
        {
            res.push_back(path);
        }
        FindPath(root->left, expectNumber-root->val);
        FindPath(root->right, expectNumber-root->val);              
        if(path.size() != 0)
            path.pop_back();
        return res;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值