记录二叉树中路径问题
1、打印所有从根节点-叶节点的路径
public void selectPaths(LinkedList<TreeNode> path, TreeNode node, List<List<TreeNode>> list) {
if (node == null) {
return;
}
path.add(node);
if (node.left == null && node.right == null) {
list.add(new ArrayList<>(path));
return;
}
if (node.left != null) {
selectPaths(path, node.left, list);
path.removeLast();
}
if (node.right != null) {
selectPaths(path, node.right, list);
path.removeLast();
}
}
2、 二叉树中从根节点出发,是否存在路径和sum = target的问题?
public boolean existsPath(LinkedList<TreeNode> path, TreeNode node, int sum, int target,
List<List<TreeNode>> r) {
if (path == null) {
return false;
}
path.add(node);
sum += node.val;
if (node.left == null && node.right == null && sum == target) {
r.add(new ArrayList<>(path));
return true;
}
boolean left = false;
if (node.left != null) {
left = existsPath(path, node.left, sum, target, r);
if (left) {
return true;
}
path.removeLast();
}
boolean right = false;
if (node.right != null) {
right = existsPath(path, node.right, sum, target, r);
if (right) {
return true;
}
path.removeLast();
}
return false;
}
3、打印从根节点-叶节点的路径和sum= 给定target的路径?
public void selectPaths(LinkedList<TreeNode> path, TreeNode node, List<List<TreeNode>> list,
int sum, int target) {
if (node == null) {
return;
}
path.add(node);
sum += node.val;
if (node.left == null && node.right == null && sum == target) {
list.add(new ArrayList<>(path));
return;
}
if (node.left != null) {
selectPaths(path, node.left, list, sum, target);
path.removeLast();
}
if (node.right != null) {
selectPaths(path, node.right, list, sum, target);
path.removeLast();
}
}
总结
- 1、关于路径和的问题,因为path是全局唯一的,所以回溯回来需要removeLast,但是sum为什么不需要sum-=node.val,因为sum+=node.val是在函数里面执行的,函数里面的sum不会影响到外面的sum。所以在回溯回来需要path.removeLast(),sum不需要-=;
- 2、递归函数返回值的问题:如果需要遍历整个树则不需要返回值,否则需要返回值。