leetcode【113】 Path Sum II【c++,递归和非递归】

问题描述:

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

源码:

就是112题目的变种leetcode【112】Path Sum。递归的方法,时间还行,内存要爆了。本来想着tmp变量也用指针,最后想想不对,那不左子树得数据影响到右子树了。没办法了,只能老老实实用vector<int> tmp(不敢加&)。后来又看了看Disucuss区里面,每次弄完pop不就完了,空间时间都省了,时间94%,空间100%。

/**
 * 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:
    void help(vector<vector<int>> &result, vector<int> &tmp, TreeNode* root, int sum){
        tmp.push_back(root->val);
        if(root->val==sum && !root->left && !root->right){
            result.push_back(tmp);
            tmp.pop_back();
            return;
        }
        if(root->left)  help(result, tmp, root->left, sum - root->val);
        if(root->right)  help(result, tmp, root->right, sum - root->val);
        tmp.pop_back();
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> result;
        if(!root)   return result;
        vector<int> tmp;
        help(result, tmp, root, sum);
        return result;
    }
};

非递归如果继续用112题的方式,可能需要多个队列,貌似中序遍历的方式会更好,虽然理解起来比122题麻烦,时间81%,空间100%(思路和第110题的非递归有点像leetcode【110】Balanced Binary Tree

/**
 * 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>> result;
        if(!root)   return result;
        vector<int> path;
        stack<TreeNode*> st;
        TreeNode *pre = NULL;
        int cursum = 0;
        while(root || !st.empty()){
            while(root){
                st.push(root);
                cursum += root->val;
                path.push_back(root->val);
                root = root->left;
            }
            root = st.top();
            if(root->right && root->right!=pre){
                root = root->right;
            }
            else{
                if(!root->left && !root->right && cursum==sum)
                    result.push_back(path);
                st.pop();
                pre = root;
                path.pop_back();
                cursum -= root->val;
                root = NULL;
            }
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值