进阶之路

首页 新随笔 管理

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;
    }
};

 

posted on 2014-08-27 16:21  进阶之路  阅读(196)  评论(0编辑  收藏  举报