Path Sum II

来源:互联网 发布:ubuntu安装完没有引导 编辑:程序博客网 时间:2024/05/18 22:15

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

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

没有用递归,想到的是用后续遍历二叉树的思想,记录上一个访问的节点,然后如果访问过或者是NULL,那么接着判断和形参的sum是否相等,如果是,则找到一个这样的路径!

/** * Definition for binary tree * 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>vec;stack<TreeNode*>s;s.push(root);TreeNode *current=root->left,*precurrent=NULL;vec.push_back(root->val);while (!s.empty()){while (current){s.push(current);vec.push_back(current->val);current = current->left;}precurrent = NULL;while (!s.empty()){current = s.top();if (current->right == precurrent){s.pop();precurrent = current;//if the current is a leaf node and the value is equal to the sumif (!current->left && !current->right && (sum == accumulate(vec.begin(), vec.end(), 0))){result.push_back(vec);}vec.pop_back();}else{current = current->right;break;}}}return result;    }};


0 0