标签:example equals public where
Total Accepted: 43473 Total Submissions: 162906My Submissions
Question Solution
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 Solution {
List<List<Integer>> x=new ArrayList<List<Integer>>();
Stack<TreeNode> stack=new Stack<TreeNode>();
void input(int s){
List<Integer> y=new ArrayList<Integer>();
Stack<TreeNode> mid=new Stack<TreeNode>();
while(!stack.isEmpty())
{
TreeNode z=stack.peek();
stack.pop();
mid.push(z);
}
int sum=0;
while(!mid.isEmpty())
{
TreeNode z=mid.peek();
sum=sum+z.val;
y.add(z.val);
mid.pop();
stack.push(z);
}
if(sum==s)
x.add(y);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null)
return x;
else
{
stack.push(root);
while(!stack.isEmpty())
{
TreeNode tn=stack.peek();
if(tn.left!=null)
{
stack.pop();
TreeNode mid=tn.left;
tn.left=null;
stack.push(tn);
stack.push(mid);
}
else if(tn.right!=null)
{
stack.pop();
TreeNode mid=tn.right;
tn.right=null;
stack.push(tn);
stack.push(mid);
}
else
{
input(sum);
while(!stack.isEmpty())
{
TreeNode v=stack.peek();
if(v.left==null&&v.right==null)
stack.pop();
else
break;
}
}
}
return x;
}
}
}
标签:example equals public where
原文地址:http://7061299.blog.51cto.com/7051299/1652962