现在来尝试将一系列的题目解决一下.
Path Sum
本题是 easy 难度的题目, 给定一个二叉树和一个和 sum, 判断是否有一条从根结点到叶子结点的路径, 使得路径上的结点的值之和与 sum 相等.
使用递归的思路 :
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
if (root.left == null && root.right == null && root.val == sum)
return true;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
不使用递归, 使用栈的思路 :
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
Stack<TreeNode> nodes = new Stack<>();
Stack<Integer> nums = new Stack<>();
nodes.push(root);
nums.push(sum);
while(!nodes.isEmpty() && root != null) {
int value = nums.pop();