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

32. Path Sum && Path Sum II

时间:2014-08-27 18:05:28      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   strong   for   ar   div   

Path Sum

OJ: https://oj.leetcode.com/problems/path-sum/

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22,

              5
             /             4   8
           /   /           11  13  4
         /  \              7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

思想: 先序遍历。若当前结点为空,返回 false; 不为空,则加上其值,若为叶子结点,则判断一次。

注意: 非路径和, 而是到叶子结点的路径和。例如: {1, 2} 1  返回: false

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
bool judge(TreeNode *root, int curSum, int& sum) {
    if(root == NULL) return false;
    curSum += root->val;
    if(!root->left && !root->right) return curSum == sum;
    return judge(root->left, curSum, sum) || judge(root->right, curSum, sum);
} 
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        return judge(root, 0, sum); 
    }
};

 

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

思路同上: 只是要记下路径。
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
void getPath(TreeNode *root, int curSum, int& sum, vector<vector<int> > &pathSet, vector<int> &path) {
    if(root == NULL) return;
    curSum += root->val; 
    path.push_back(root->val);
    if(!root->left && !root->right && curSum == sum)  
        pathSet.push_back(path);
    getPath(root->left, curSum, sum, pathSet, path);
    getPath(root->right, curSum, sum, pathSet, path);
    path.pop_back();
}
class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> >pathSet;
        vector<int> path;
        getPath(root, 0, sum, pathSet, path);
        return pathSet;
    }
};

 

32. Path Sum && Path Sum II

标签:style   blog   http   color   io   strong   for   ar   div   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3939732.html

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