【LeetCode】112.路径总和(递归和迭代实现,Java)

题目地址:https://leetcode-cn.com/problems/path-sum/

题目

  1. 路径总和
    给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

    5
             / 
            4   8
           /   / 
          11  13  4
         /        
        7    2      1

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

递归实现

public boolean hasPathSum(TreeNode root, int sum) {
		if(root == null) return false;
		sum -= root.val;
		if(root.left == null) && (root.right == null)
			return (sum == 0 );
		return hasPathSum(root.left,sum) || hasPathSum(root.right,sum);
    }

迭代实现

	public boolean hasPathSum(TreeNode root, int sum) {
	if(root == null ) return false;
	Stack<TreeNode> node = new Stack<>();
	Stack<Integer>  path = new Stack<>();
	node.push(root);
	path.push(root.val);
	while(!node.isEmpty()){
		TreeNode t = node.pop();
		int val = path.pop();
		if(t.left == null && t.right == null && val == sum) 
			return true;
		if(t.left!=null){
			node.push(t.left);
			path.push(t.left.val+val);
			}
		if(t.right!=null){
			node.push(t.right);
			path.push(t.right.val+val);
			}		
}
	return false;
}
原文地址:https://www.cnblogs.com/hzcya1995/p/13308079.html