Leetcode437. 路径总和 III
相似题目:
Leetcode112. 路径总和
Leetcode113. 路径总和 II
题目:
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
题解:
迭代:
运用二叉树的前序遍历方法:
java代码:
/**
* @param root
* @param sum
* @return
*/
public static int pathSum(TreeNode root, int sum) {
List<TreeNode> list = new ArrayList<>();
if (root == null) return 0;
LinkedList<TreeNode> stack = new LinkedList<>();
//Stack<TreeNode> stack = new Stack<>();
stack.push(root);
int count = 0;
while (!stack.isEmpty()) {
TreeNode node = stack.removeLast();
//TreeNode node = stack.pop();
if (node.right != null) {
stack.addLast(node.right);
//stack.push(node.right);
}
if (node.left != null) {
stack.addLast(node.left);
//stack.push(node.left);
}
if (list.size() != 0) {
while (true) {
// 如果当前节点是路径pathList的子节点,是左或者右节点,
//我们什么都不做break,随后把当前节点加入pathList
if (list.get(list.size() - 1).left == node || list.get(list.size() - 1).right == node) {
break;
} else {
//如果不是,我们就删除最后一个,一直找到当前节点的父节点
list.remove(list.size() - 1);
}
}
}
list.add(node);
int tmp = 0;
for (int i = list.size() - 1; i >= 0; i--) {
tmp += list.get(i).value;
if (tmp == sum) {
count++;
}
}
}
return count;
}
本文提供了一种解决LeetCode437路径总和III问题的方法,该问题要求在二叉树中查找所有路径和等于给定数值的路径数量。通过迭代方式实现,使用前序遍历策略,详细介绍了算法思路并提供了Java代码实现。
585

被折叠的 条评论
为什么被折叠?



