Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
DFS整棵树.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private void dfs(TreeNode node, int residual, List<Integer> path, List<List<Integer>> res) {
if (node == null) {
return;
}
path.add(node.val);
residual -= node.val;
if (node.left == null && node.right == null && residual == 0) {
res.add(new ArrayList<>(path));
}
dfs(node.left, residual, path, res);
dfs(node.right, residual, path, res);
residual += node.val;
path.remove(path.size() - 1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
dfs(root, sum, new ArrayList<>(), res);
return res;
}
}
看着和inorder很像, 区别在于当退回到中间节点时, 不能直接pop, 否则path将不再包含它, 而是要检查它的右子树是否存在, 并把右子树pushLeft. 但如果每次都pushLeft则无法正常让中间节点退出, 因此还要把上个退出的节点记下来, 看是否和中间节点的right一致, 当一致时意味着右子树已经查过了, 不需要再pushLeft了.
/**
* 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) {
stack<TreeNode*> s;
vector<vector<int>> r;
vector<int> p;
int psum = 0;
const auto push_left = [&](TreeNode *cur) {
while (cur != NULL) {
psum += cur->val;
p.push_back(cur->val);
s.push(cur);
cur = cur->left;
}
};
TreeNode *pre;
push_left(root);
while (!s.empty()) {
const auto cur = s.top();
if (cur->right != NULL && cur->right != pre) {
push_left(cur->right);
continue;
}
if (cur->left == NULL && cur->right == NULL && psum == sum) {
r.push_back(p);
}
s.pop();
psum -= cur->val;
p.pop_back();
pre = cur;
}
return r;
}
};