leetcode-112 路径总和
计算根节点到叶子节点的和,然后和目标值进行比较。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private boolean flag = false;
public void findPath(TreeNode root, int curSum, int aim){
// 找到了目标值,不在遍历
if (flag) return;
if (root.left == null && root.right == null){
if (curSum + root.val == aim) flag = true;
return ;
}
if (root.left != null) findPath(root.left, curSum + root.val, aim);
if (root.right != null) findPath(root.right, curSum + root.val, aim);
}
public boolean hasPathSum(TreeNode root, int sum) {
// 判空!!! 又忘了
if (root == null) return false;
findPath(root, 0, sum);
return flag;
}
}
本文介绍了一个简单的二叉树路径求和算法,通过递归方式计算从根节点到叶子节点的所有路径之和,并判断该和是否等于给定的目标值。此算法适用于LeetCode上的题目“路径总和”,通过对二叉树节点的遍历实现解决方案。
513





