leetcode question 113: Path Sum II

问题:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

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

分析:

这道题和Leetcode 112 的不同就是前者要求找出所有的路径,后者只需要判断有没有。不过方法可以通用,这里可以看作很多棵树进行判断,比如对以5为根节点的树判断有没有和为22的路径,就变成了分别对以4和8为根节点的树进行判断有没有和为17的路径。同理可以递归判断。

 

代码:

/**
 * 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>> res;
        if( root == NULL ){
            return res;
        }
        
        //如果刚好相等,检查是不是叶子节点
        if( root->val == sum ){
            if( root->left == NULL && root->right == NULL ){
                vector<int> temp;
                temp.insert(temp.begin(),root->val);
                res.push_back(temp);
                return res;
            }
        }
        
        //对左右子节点进行递归操作
        vector<vector<int>> leftSum = pathSum(root->left,sum- root->val );
        vector<vector<int>> rightSum = pathSum(root->right, sum - root->val );
        
        //对返回的结果进行整理,并加入当前节点的值
        for( int i = 0 ; i < leftSum.size() ; i ++ ){
            vector<int> temp = leftSum[i];
            temp.insert(temp.begin(),root->val);
            res.push_back(temp);
        }
        
        for( int i = 0 ; i < rightSum.size() ; i ++ ){
            vector<int> temp = rightSum[i];
            temp.insert(temp.begin(),root->val);
            res.push_back(temp);
        }
        
        return res;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值