LeetCode:Path Sum I &&II

路径总和问题解析
本文介绍了二叉树路径总和问题的两种解决方法,包括利用栈进行迭代处理和使用递归算法。通过具体实例展示了如何查找从根节点到叶子节点的路径是否符合给定的总和。

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.

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

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

第一种方法可以利用栈,非叶子依次入栈,将数值累加起来,一直加到叶子节点此时刚好等于sum,返回true,若不等,处理该叶子节点的父节点,一直到栈空为止。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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;
        }
        TreeNode p=root,q;
        Stack<TreeNode> stack=new Stack<TreeNode>();
        stack.add(p);
        while(!stack.isEmpty())
        {
            p=stack.peek();
            if(p.left==null && p.right==null)
            {
                p=stack.pop();
                if(stack.isEmpty())return false;
                q=stack.peek();
                if(q.left==p)q.left=null;
                if(q.right==p)q.right=null;
                continue;
            }
            if(p.left!=null)
            {
                q=p.left;
                q.val=q.val+p.val;
                if(q.left==null && q.right==null)
                {
                    if(q.val==sum)return true;
                    else 
                    {
                        p.left=null;
                        continue;
                    }
                }
                else {
                    stack.add(q);
                    continue;
                }
            }
            if(p.right!=null)
            {
                q=p.right;
                q.val=q.val+p.val;
                 if(q.left==null && q.right==null)
                {
                    if(q.val==sum)return true;
                    else 
                    {
                        p.right=null;
                        continue;
                        }
                }
                else {
                    stack.add(q);
                    continue;
                }
                
            }//else if
        }    
     return false;       
    }
        
}
第二种方法直接利用递归,思路简单:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)return false;
        if(root.left==null && root.right==null && root.val==sum)return true;
       return  (root.left!=null &&hasPathSum(root.left,sum-root.val) ) || (root.right!=null  && hasPathSum(root.right,sum-root.val));
    
}
}

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]
]

第一种方法与I中的方法一类似,需要保存每一步的值进入in list,如果最终值等于sum,将in list 加入最终返回的list中。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    ArrayList<Integer> copyNewList(ArrayList<Integer> in)
    {
        int size=in.size();
        ArrayList<Integer> out=new ArrayList<Integer>();
        Iterator<Integer> it=in.iterator();
        while(it.hasNext())out.add(it.next());
        out.remove(size-1);
        return out;
    }
    
    
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
        if(root==null)return list;
        Stack<TreeNode> stack=new Stack<TreeNode>();
        TreeNode p=root,q;
        ArrayList<Integer> in;
        if(root.left==null && root.right==null)
        {
            if(root.val==sum){
                in=new ArrayList<Integer>();
                in.add(root.val);
                list.add(in);
            }
           return list;
        }
        stack.add(p);
        in=new ArrayList<Integer>();
        in.add(p.val);
        while(!stack.isEmpty())
        {
           p=stack.peek();
           if(p.left==null && p.right==null)
           {
               q=stack.pop();
               if(stack.isEmpty())return list;
               p=stack.peek();
               if(p.left==q)p.left=null;
               if(p.right==q)p.right=null;
            continue;   
           }
            if(p.left!=null)
            {
                q=p.left;
                if(q.left==null && q.right==null)
                {
                    if(p.val+q.val==sum){
                        
                    
                        in.add(q.val);
                        list.add(in);
                        in=copyNewList(in);
                    }
                    p.left=null;
                    continue;
                }
                else
                {
                    in.add(q.val);
                    q.val=p.val+q.val;
                    stack.add(q);
                    continue;
                }
            }     
                
            if(p.right!=null)
            {
                    q=p.right;
                if(q.left==null && q.right==null)
                {
                    if(p.val+q.val==sum){
                        
                    
                        in.add(q.val);
                        list.add(in);
                        in=copyNewList(in);
                    }
                    p.right=null;
                    continue;
                }
                else {
                    in.add(q.val);
                    q.val=p.val+q.val;
                    stack.add(q);
                    continue;
                    
                }
                
                
            }// if p.right
           
           
        }//end while
        
        return list;
    }
}

第二种方法类似I中的方法2,利用递归:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> in = new ArrayList<Integer>();
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
		if(root == null)return res;
		recursion(root, sum);
		return res;
    }
    public void recursion(TreeNode root,int sum)
	{
		if(root.left == null && root.right == null)
		{
			in.add(root.val);
			int sum1 = 0;
			for(int i = 0; i < in.size(); i++)
			{
				sum1 += in.get(i);
			}
			if(sum1 == sum)
				res.add(new ArrayList<Integer>(in));
			return ;
		}
		    in.add(root.val);
		if(root.left != null)
		{	
			recursion(root.left,sum);
			in.remove(in.size() - 1);
		}
		if(root.right != null)
		{
			recursion(root.right,sum);
			in.remove(in.size() - 1);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值