leetcode-剑指34-OK

// language C with STL(C++)
// 剑指34
// https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
// 同主站113
// https://leetcode-cn.com/problems/path-sum-ii/


/**
 * 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) {
    	// 维护一个int change表示vector内的int之和,后续遍历访问root为根的二叉树,访问一个节点 = 检查if change == sum
    	vector<vector<int>> answer;
    	vector<int> gongju;
    	int change = 0;


		stack<TreeNode*> ans;	//用来遍历的栈
		TreeNode* p=root;
		TreeNode* pre = NULL;
		TreeNode* temp;
		while(p || !empty(ans)){
			if(p){
				ans.push(p);
				gongju.push_back(p->val);
				change += p->val;
				p= p->left;
			}else{
				p = ans.top();
				if((p->right != NULL) && (p->right !=pre)){
					p = p->right;
					ans.push(p);
					gongju.push_back(p->val);
					change += p->val;
					p = p->left;
				}else{
					temp = ans.top();
					if(change==sum){
						if((temp->left==NULL)&&(temp->right ==NULL)){
							vector<int> what(gongju);
							answer.push_back(what);
						}
					}
					change -= temp->val;
					gongju.pop_back();
					ans.pop();
					pre = temp;
					p = NULL;
				}
			}
		}
        return answer;
    }
};
posted @ 2021-02-03 17:02  RougeBW  阅读(38)  评论(0编辑  收藏  举报