标签:
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] ]
[Solution]
非递归,后续遍历。
1 { 2 vector<vector<int> > result; 3 vector<int> tree_nodes; 4 stack<TreeNode *> stree; 5 TreeNode *visit = root, *last_visit = NULL, *peek = NULL; 6 7 while (!stree.empty() || visit != NULL) 8 { 9 if (visit != NULL) 10 { 11 stree.push(visit); 12 tree_nodes.push_back(visit->val); 13 sum -= visit->val; 14 if (visit->left == NULL && visit->right == NULL) // leaf node 15 { 16 if (0 == sum) 17 result.push_back(tree_nodes); 18 } 19 visit = visit->left; 20 } 21 else 22 { 23 peek = stree.top(); 24 if (peek->right != NULL && peek->right != last_visit) 25 { 26 visit = peek->right; 27 } 28 else 29 { 30 last_visit = peek; 31 stree.pop(); 32 sum += tree_nodes.back(); 33 tree_nodes.pop_back(); 34 } 35 } 36 } 37 38 return result; 39 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4278717.html