LeetCode 112Path 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.
给定一棵二叉树和sum值,求出是否存在完整路径(从根节点到叶子节点)的值相加等于sum。有则返回true,没有则返回false。
113Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
给出所有从根节点到叶子节点的值相加为sum的路径,是第一题的升级版本。
解题思路:这两题的另层含义无非是将所有根到叶子的路径遍历一下,然后将路径上的值相加,与sum值比较。学习了树的同学都会觉得,遍历到叶子容易,但是中间节点出现右子树,如何返回这个右子树的根节点,确实有点难解决。这时候就是考验用栈(Stack)技巧的时候了。
首先第一题:
public boolean hasPathSum(TreeNode root, int sum) {
Stack<TreeNode> stack=new Stack<TreeNode>();//用来记录返回上层节点的栈
Stack<Integer> keyNumStack=new Stack<Integer>();//stack中每个节点到根节点的数值和
int total=0;
TreeNode current=root;
while(!stack.isEmpty()||current!=null)//节点遍历
{
if(current!=null)
{
stack.push(current);//节点压栈
total+=current.val;
keyNumStack.push(total);
current=current.left;
}else
{
current=stack.pop();//左子树为空,弹出
total=keyNumStack.pop();//节点到根节点的数值和
if(current.right==null)
{//判断是否是叶子节点,左右节点为空,将total与sum比较
if(total==sum&&t.left==null)return true;
}
current=current.right;
}
}
return false;
}
第二题:
public List<List<Integer>> pathSum(TreeNode root, int sum) {
Stack<TreeNode> stack=new Stack<TreeNode>();
Stack<Integer> keyStack=new Stack<Integer>();
Stack<TreeNode> stack1=new Stack<TreeNode>();用来记录当前节点到根节点中的所有节点
List<Integer> list=null;
List<List<Integer>> result=new ArrayList<List<Integer>>();
int total=0;
TreeNode current=root;
while(!stack.isEmpty()||current!=null)
{
if(current!=null)
{
stack.push(current);
stack1.push(current);
total+=current.val;
keyStack.push(total);
current=current.left;
}else
{
current=stack.pop();
total=keyStack.pop();
if(current.right==null&&t.left==null)
{
if(total==sum)
{
list=new ArrayList<Integer>();
for(int i=0;i<stack1.size();i++)
{
list.add(stack1.get(i).val);
}
result.add(list);
}
}else
{//stack遍历过程中的根节点会先于右节点弹出,但根节点的右子树访问完的时候,再弹出的是根节点的上层节点。这时候需要用stack1来专门记录根节点到当前节点的所有节点,而不仅仅是有左右子树的节点。具体理解需要结合题目去详细分析
while(!stack1.isEmpty())
{
if(stack1.peek()==current)break;
stack1.pop();
}
}
current=current.right;
}
}
return result;
}