第34-2题:LeetCode113. Path Sum II

题目

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22

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

返回:

[
   [5,4,11,2],
   [5,8,4,5]
]

 


考点

1.前序遍历

2.stack

3.递归


思路


代码

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public: 
    
        vector<vector<int>> FindPath(TreeNode* root, int sum) {
        // 变量
        std::vector<int> path;
        std::vector<vector<int>> ret;
        int cur = 0;
        
        // 入口
        if(!root)
            return ret; 
        
        // 出口
        return FindPath(root,sum,path,cur,ret);
    }
    
    
    vector<vector<int>> FindPath(TreeNode* root,int sum,vector<int> &path,int cur,vector<vector<int>> &ret)
    { 
        // 1.更新cur 和 path
        cur+=root->val;
        path.push_back(root->val);
        
        // 标记叶子节点bool
        bool isLeaf = !root->left && !root->right;
        
        // 2.如果是叶子节点且路径之和等于目标值,保存path到ret中,清空path
        if(isLeaf && cur == sum )
        {
            ret.push_back(path);
            path.pop_back();
            return ret;
        }
        
        // 3.如果不是叶子节点,访问其左右子树
        if(root->left)
        {
            ret = FindPath(root->left,sum,path,cur,ret);
        }
        
        if(root->right)
        {
            ret = FindPath(root->right,sum,path,cur,ret);
        }
        // 4.递归结束之前,还原到父节点操作
        cur-=root->val;
        path.pop_back();
        
        
        // 5.出口
        return ret;
    }    
    
};

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
static const void* ___ = []() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	return nullptr;
}();
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> result;
        list<int> cur;
        pathSum(result, cur, root, sum);
        return result;
    }
private:
    void pathSum(vector<vector<int>> &result, list<int> &cur, TreeNode *root, int sum) {
        if (!root) return;
        if (!root->left && !root->right)
        {
            if (sum == root->val)
            {
                result.emplace_back(cur.begin(), cur.end());
                result.back().push_back(sum);
            }
        } else
        {
            cur.push_back(root->val);
            pathSum(result, cur, root->left, sum - root->val);
            pathSum(result, cur, root->right, sum - root->val);
            cur.pop_back();
        }
    }
};

问题

1.执行用时快的原因

解析 static auto x = []() { std::ios::sync_with_stdio(false);std::cin.tie(nullptr);return 0;}()

posted @ 2019-02-12 23:59  lightmare  阅读(117)  评论(0编辑  收藏  举报