I. Title Description
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 sum = 22
and,
5 4 8 / 11 13 4 / \ 7 2 5 1
Return
[ [5,4,11,2], [5,8,4,5]]
Two. Topic analysis
This problem is similar to path sum, but the problem requires finding all paths that are equal to the given value and must traverse all paths. After finding the path that is satisfied, you cannot return directly, but add it to one vector<vector<int>>
. In the process of finding, each node passes through, using one vector<int>
to record all the nodes in that path. It is important to note that when you enter each node, the value of the node is first set to the value of the node push
vector
at exit, pop
so you can avoid situations where you sometimes forget the pop
value of the node.
The time complexity of the method is O (n) and the space complexity is O (logn).
Three. Sample code
structtreenode{intVal TreeNode *left; TreeNode *right; TreeNode (intx): Val (x), left (null), right (null) {}};classsolution{ Public: vector<vector<int>>Pathsum (treenode* root,intSUM) { vector<vector<int> >Result; vector<int>Tmpresult; Pathsum (Root, Sum, Result, Tmpresult);returnResult; }Private:voidPathsum (treenode* root,intSum vector<vector<int> >&result, vector<int>&tmpresult) {if(!root)return;if(!root->left &&!root->right && root->val = = sum) {tmpresult.push_back (sum); Result.push_back (Tmpresult);//Pop the leaf nodeTmpresult.pop_back ();return; }intSumchild = sum-root->val; Tmpresult.push_back (Root->val); Pathsum (Root->left, Sumchild, Result, Tmpresult); Pathsum (Root->right, Sumchild, Result, Tmpresult); Tmpresult.pop_back (); }};
Four. Summary
As with path sum, it is resolved with DFS.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Note: Path Sum II