zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    病毒软件测试代码
    如何将WIN安全设置重置回默认值
    今天值班非常不爽。
    FTP命令(2)
    WORD操作
    DELPHI事务
    DELPHI一些常用的技巧
    钩子学习心得
    (转 )Delphi指针如何指向使用with开域语句创建的无名组件对象
    WebBrowser 操作记要 (DELPHI)
  • 原文地址:https://www.cnblogs.com/gallien/p/14367964.html
Copyright © 2011-2022 走看看