您的位置:首页 > 产品设计 > UI/UE

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. For example: Given the below binary tree andsum =

2016-05-20 11:33 585 查看
Givenabinarytreeandasum,determineifthetreehasaroot-to-leaf
pathsuchthataddingupallthevaluesalongthepathequalsthegiven
sum.

Forexample:

Giventhebelowbinarytreeandsum=22,

5
/\
48
//\
11134
/\\
721

returntrue,asthereexistaroot-to-leafpath5->4->11->2whichsumis22.

代码1

importjava.util.ArrayList;

classTreeNode{
intval;
TreeNodeleft;
TreeNoderight;
TreeNode(intx){val=x;}
}
publicclassSolution{
ArrayList<ArrayList<Integer>>result=newArrayList<ArrayList<Integer>>();
ArrayList<Integer>arr=newArrayList<Integer>();
publicbooleanhasPathSum(TreeNoderoot,intsum){
if(root==null)returnfalse;
isPath(root,0,sum);
if(result.isEmpty())returnfalse;
elsereturntrue;

}
privatevoidisPath(TreeNoderoot,intsum,inttarget){
if(root==null)return;
else{
sum+=root.val;
arr.add(root.val);
if(root.left==null&&root.right==null&&sum==target){
result.add(newArrayList<Integer>(arr));
}
isPath(root.left,sum,target);
isPath(root.right,sum,target);
arr.remove(arr.size()-1);
sum-=root.val;
}

}
}

代码二:


importjava.util.ArrayList;

classTreeNode{
intval;
TreeNodeleft;
TreeNoderight;
TreeNode(intx){val=x;}
}
publicclassSolution{

publicbooleanhasPathSum(TreeNoderoot,intsum){
returnhasPathSumHelper(root,sum);
}

privatebooleanhasPathSumHelper(TreeNoderoot,intsum){
//TODOAuto-generatedmethodstub
if(root==null)returnfalse;
if(root.left==null&&root.right==null&&sum==root.val)returntrue;
returnhasPathSumHelper(root.left,sum-root.val)||hasPathSumHelper(root.right,sum-root.val);
}
}





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: