Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22
,
5
/
4 8
/ /
11 13 4
/
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
一般的二叉树怎么遍历来着,就是DC吧
sum = sum + left或者sum + right
下次用的是什么呢?一直加左边也不对啊
逆向思维,好吧。用的是traverse,就类似于相同二叉树的那种写法
//conquer的具体实现:左右都是空,只检查节点本身。 if (root.left == null && root.right == null) return (root.val == sum);
因为是在左边递归,所以参数应该是左节点root.left
只有左右节点都为空的时候,才需要考虑root.val == sum这样根本性的问题
最后递归的时候,值是减去的root.val,而且左右两边有一条路径符合即可
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean hasPathSum(TreeNode root, int sum) { //cc if (root == null) return false; //conquer的具体实现:左右都是空,只检查节点本身。 if (root.left == null && root.right == null) return (root.val == sum); return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }