首页 > 代码库 > 二叉树的路径和

二叉树的路径和

给定一个二叉树,找出所有路径中各节点相加总和等于给定目标值的路径。一个有效的路径,指的是从根节点到叶节点的路径。

样例:给定一个二叉树,和 目标值 = 5:

     1
    / \
   2   4
  / \
 2   3


返回:
[
  [1, 2, 2],
  [1, 4]
]

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root the root of binary tree
     * @param target an integer
     * @return all valid paths
     */
    vector<vector<int>> V;
    vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
        vector<int> v;
        if (root == NULL) return V;
        int sum = 0;
        find(root, target, v, sum);
        return V;
    }
    
    void find(TreeNode *root, int target, vector<int> v, int sum) {
        v.push_back(root->val);
        sum += root->val;
        if (sum == target && root->left == NULL && root->right == NULL) {
            V.push_back(v);
        }
        if (root->left != NULL) {
            find(root->left, target, v, sum);
        }
        if (root->right != NULL) {
            find(root->right, target, v, sum);
        }
        sum -= root->val;
        v.pop_back();
    }
 
};

 

二叉树的路径和