剑指Offer二叉树中和为某一值的路径(C++/Java双重实现)

1.问题描述

在这里插入图片描述

2.问题分析

本题采用回溯加先序遍历思想,思路大致是:
1.按照 “根、左、右” 的顺序,遍历树的所有节点
2.: 在先序遍历中,记录从根节点到当前节点的路径。当路径为 、
(1)根节点到叶节点形成的路径 且
(2)各节点值的和等于目标值 sum 时,将此路径加入结果列表。

3.代码实现

3.1C++代码

/**
 * 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>> VEC;
    vector<int> vec;
    
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
     recur(root,sum);
     return VEC;

    }
    void recur(TreeNode *root,int target)
    {
        if(root==NULL)
        return;
        target-=root->val;
        vec.push_back(root->val);
        if(target==0&&root->left==NULL&&root->right==NULL)
        {
            VEC.push_back(vec);
        }
        recur(root->left,target);
        recur(root->right,target);
        vec.pop_back();

    }
};

3.2Java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    LinkedList<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>(); 
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        recur(root, sum);
        return res;
    }
    void recur(TreeNode root, int tar) {
        if(root == null) return;
        path.add(root.val);
        tar -= root.val;
        if(tar == 0 && root.left == null && root.right == null)
            res.add(new LinkedList(path));
        recur(root.left, tar);
        recur(root.right, tar);
        path.removeLast();
    }
}


猜你喜欢

转载自blog.csdn.net/qq_45737068/article/details/107943394