考察DFS
/*
* @lc app=leetcode.cn id=112 lang=java
*
* [112] 路径总和
*
* https://leetcode-cn.com/problems/path-sum/description/
*
* algorithms
* Easy (44.17%)
* Total Accepted: 13.9K
* Total Submissions: 30.5K
* Testcase Example: '[5,4,8,11,null,13,4,7,2,null,null,null,1]\n22'
*
* 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
*
* 说明: 叶子节点是指没有子节点的节点。
*
* 示例:
* 给定如下二叉树,以及目标和 sum = 22,
*
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ \
* 7 2 1
*
*
* 返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
*
*/
二叉树类
//Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
我的java代码,递归,(我的代码还没找到最小递归单元。。。)
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
if (root.val == sum && root.left == null && root.right == null) return true;
int rootVal = root.val;
sum = sum - rootVal;
if (root.left != null) {
if (root.left.val == sum && root.left.left == null && root.left.right == null) {
return true;
}
}
if (root.right != null) {
if (root.right.val == sum && root.right.left ==null && root.right.right == null) {
return true;
}
}
return (hasPathSum(root.left, sum) || hasPathSum(root.right, sum));
}
}
大佬的java代码,递归
public boolean hasPathSum(TreeNode root, int sum) {
// recursion method
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);
}
大佬的java代码,栈
public boolean hasPathSum(TreeNode root, int sum) {
// iteration method
if (root == null) {return false;}
Stack<TreeNode> path = new Stack<>();
Stack<Integer> sub = new Stack<>();
path.push(root);
sub.push(root.val);
while (!path.isEmpty()) {
TreeNode temp = path.pop();
int tempVal = sub.pop();
if (temp.left == null && temp.right == null) {if (tempVal == sum) return true;}
else {
if (temp.left != null) {
path.push(temp.left);
sub.push(temp.left.val + tempVal);
}
if (temp.right != null) {
path.push(temp.right);
sub.push(temp.right.val + tempVal);
}
}
}
return false;
}