标签:
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.
思路:
简单的DFS
我的代码1:
public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; if(root.left == null && root.right == null) { if(root.val == sum) return true; else return false; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
我的代码2:
可以进行更加简洁的改进
public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root == null) return false; if(root.left == null && root.right == null) { return root.val == sum; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
学习之处:
对于if else 简单的相等不相等,往往可以转换成一条语句,使程序更加简洁明了。
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4328916.html