Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
通过一个p指针,遍历 二叉树,并将每次的值 保存在 sum2 中 。
遇到右节点,将右节点+depth 保存在 temp中,当再次使用 该节点时,根据depth 将sum2中的长度削减成 depth-1
/** * 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> pathSum(TreeNode* root, int sum) { vector > re; if(root==NULL) return re; TreeNode *p=root; int depth=1; vector > temp; // 保存右节点+depth vector sum2; // 保存一条路径的所有点值 pair t=make_pair(root,depth); // temp.push_back(t); while(!temp.empty()||p!=NULL){ sum2.push_back(p->val); if(p->left!=NULL){ if(p->right!=NULL){ temp.push_back(make_pair(p->right,depth+1)); } p=p->left; depth++; } else{ if(p->right==NULL){ int result=0; for(int i=0;i right; depth++; } } } return re; }};