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

【Path Sum II】cpp

时间:2015-05-17 23:29:44      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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 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> > ret;
            // Terminal conditon 1 : to the null (not leaf node)
            // even if sum equals zero at the time, becasue not leaf node
            // so it is also not the available solution path
            if (!root) return ret;
            // Terminal condition 2 : leaf node
            if ( !root->left && !root->right )
            {
                // if leaf node‘s val equal sum
                if ( sum==root->val )
                {
                    vector<int> tmp;
                    tmp.insert(tmp.begin(),root->val);
                    ret.push_back(tmp);
                }
                return ret;
            }
            // not leaf node : move forward to left and right
            vector<vector<int> > l = Solution::pathSum(root->left, sum - root->val);
            vector<vector<int> > r = Solution::pathSum(root->right, sum - root->val);
            for ( size_t i = 0; i<l.size(); ++i )
            {
                l[i].insert(l[i].begin(), root->val);
                ret.push_back(l[i]);
            }
            for ( size_t i = 0; i<r.size(); ++i )
            {
                r[i].insert(r[i].begin(), root->val);
                ret.push_back(r[i]);
            }
            return ret;
    }
};

tips:

与Path Sum思路类似(http://www.cnblogs.com/xbf9xbf/p/4508964.html

不同的地方是:只要不是leaf node,left和right两边的情况都要考虑。

============================================

并且有个地方需要缕清思路:如果递归时遇上root==NULL,直接返回空的ret是否合理?如果此时的sum==0呢?

root==NULL有以下三种情况

1. 如果整棵树是空树:即使sum==0也不满足条件

2. 某个非leaf node的left(或right)为空:则即使此时sum==0,往left(或right)方向走会得到root=NULL,因为此时root不是leaf node也不成立

【Path Sum II】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4510667.html

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