leetcode 之 path sum

题目: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.


源代码:

import java.util.Stack;

public class PathSum {

	boolean result;
	public  boolean hasPathSum(TreeNode root, int sum){
		if(root == null){
			return false;
		}else{
			int curSum = 0;
			Stack<Integer> path = new Stack<Integer>();
//			boolean result = false;
			findPathSum(root, path, curSum, sum);
			return result;
		}
	}
	private  void findPathSum(TreeNode root, Stack<Integer> path, int curSum, int sum){
		if(result){
			return;
		}
		curSum += root.val;
		boolean isLeaf = root.left == null && root.right == null;
		path.push(root.val);
		if(curSum == sum && isLeaf){
			this.result = true;
			return;
		}
		if(root.left != null){
			findPathSum(root.left, path, curSum, sum);
		}
		if(root.right != null){
			findPathSum(root.right, path, curSum, sum);
		}
		path.pop();
	}
	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
		int sum = 1;
		PathSum ps = new PathSum();
		System.out.println(ps.hasPathSum(root, sum));

	}

}

可能代码中还有一些不成熟的地方,请观者不吝指教,谢谢。


Path Sum II :  Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and  sum = 22 ,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]


源代码:

public class PathSumII {

	public static List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(root == null){
        	return result;
        }
        int curSum = 0;
        List<Integer> path = new ArrayList<Integer>();
        pathSum(root, result, path, curSum, sum);
        return result;
    }
	private static void pathSum(TreeNode root, List<List<Integer>> result,
			List<Integer> path, int curSum, int sum) {
		curSum += root.val;
		path.add(root.val);
		boolean isLeaf = root.left == null && root.right == null;
		if(sum == curSum && isLeaf){
			List<Integer> tmp = new ArrayList<Integer>();
			for(int x : path){
				tmp.add(x);
			}
			result.add(tmp);
		}
		
		if(root.left != null){
			pathSum(root.left, result,path, curSum, sum);
		}
		if(root.right != null){
			pathSum(root.right, result, path, curSum, sum);
		}
		path.remove(path.size() - 1);
		
		
	}
	public static void main(String[] args) {
		
		TreeNode root = new TreeNode(1);
		System.out.println(PathSumII.pathSum(root, 1));

	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值