码迷,mamicode.com
首页 > 其他好文 > 详细

Path Sum

时间:2015-01-25 21:06:41      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:leetcode   path sum   二叉树   遍历   

1. 问题描述

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


2. 思路

本质是二叉树的先序遍历! 先序遍历二叉树,将每次访问的节点值相加,直到叶子节点,然后判断这条到叶子节点的路径上所有节点的值的和是否和给定值相等,相等则将这条路径所有节点的值所组成的vector加入vecRet中。 存放路径显然是一个栈,题目中要求返回vector<vector<int>>,就将路径上的节点值放入vector<int>中,递归返回父节点的时候需要将节点从vector<int>中去掉。


3. 代码

    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int>> vecRet;
        if (root == NULL)
            return vecRet;
        int currentSum = 0;
        vector<int> path;
        pathSum (root , sum , currentSum , path , vecRet);
        return vecRet;
    }
    
    void pathSum (TreeNode* root , int sum , int currentSum , vector<int> &path , vector<vector<int>> &vecRet)
    {
        if (root == NULL)
            return ;
        TreeNode* pNode = root;
        path.push_back(pNode->val);
        currentSum += pNode->val;
        bool isLeaf = pNode->left == NULL && pNode->right == NULL;
        if (isLeaf && currentSum == sum) 
            vecRet.push_back(path);
        if (pNode->left)
            pathSum (root->left , sum , currentSum , path , vecRet);
        if (pNode->right)
            pathSum (root->right ,sum , currentSum , path , vecRet);
        currentSum -= pNode->val;
        path.pop_back();
    }



Path Sum

标签:leetcode   path sum   二叉树   遍历   

原文地址:http://blog.csdn.net/u012458164/article/details/43117687

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!