[LeetCode]路径和2

题目: 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

返回:
[
[5,4,11,2],
[5,8,4,5]
]
分析:由于合法路径要求为根节点到叶子节点(root to leaf),搜索算法我们采用DFS(深度优先搜索),搜索路径采用中序遍历(左-根-右),由于满足要求的路径可能非唯一,搜索中需要注意“回溯”。
结合题目中的例子,简述思路如下:
1.采用中序遍历,则从根节点5起,首先搜索左孩子节点,一直到达叶子节点为止,第一条合法路径为:5-4-11-7,检验路径和是否满足约束条件(sum==22);
2.若满足则将路径保存起来;
3.然后,当前路径尾端数据弹出,剩余5-4-11,返回,相当于回到根节点11;
4.继续搜索右孩子结点,2为叶子节点,因而合法路径为:5-4-11-2,检验其是否满足约束条件;
5…..

【注意事项】执行当前路径尾端数据弹出的操作有两个位置:
1.遍历至叶子节点,形成合法路径,在检验路径是否满足约束条件并保存后,弹出末端数据,返回,如此便可回到最近的根节点,然后继续搜索该根节点的子节点;
2.某一根节点的左右子节点遍历完毕,如根节点11的子节点7和2遍历完毕,须返回上一层,这时候需要弹出根节点11,则当前搜索路径变为:5-4;根节点4没有右叶子节点,弹出4,返回上一层5,根节点5有右子节点,继续中序遍历…

package tree;

import java.util.ArrayList;
import java.util.List;
public class PathSum {
    public List<List<Integer>> pathSum(TreeNode root, int sum) 
    {
       List<List<Integer>> result=new ArrayList<List<Integer>>();//List接口变量用的ArrayList类对象实例化
       List<Integer> temp=new ArrayList<Integer>();

       if(root==null)return result;
       DFS(result,temp,root,sum);

       return result;
    }

    void DFS(List<List<Integer>> result,List<Integer> temp,TreeNode root,int sum)
    {
       if(root==null)return;
       if(root.left==null&&root.right==null)
       {
           temp.add(root.val);
           if(sumOfPath(temp)==sum)
               result.add(new ArrayList<Integer>(temp));//一定要注意
           temp.remove(temp.size()-1);
           return;
       }
       else
       {
           temp.add(root.val);
           DFS(result,temp,root.left,sum);
           DFS(result,temp,root.right,sum);
           temp.remove(temp.size()-1);
       }
   }

   int sumOfPath(List<Integer> temp)
   {
       int sum=0;
       for(int i=0;i<temp.size();i++)
       {
           sum+=temp.get(i);
       }
       return sum;
   }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值