二叉树中所有的路径(从根节点到叶子结点)

 1 import java.util.ArrayList;
 2 
 3 /**
 4  * 寻找最短的二叉搜索的路径,从根节点到叶子结点
 5  * 
 6  * @author jinfeng
 7  *
 8  */
 9 public class FindShortestBTPath {
10 
11     // 用来记录所有的路径
12     private ArrayList<ArrayList<Integer>> allPaths = new ArrayList<ArrayList<Integer>>();
13     // 用来记录一条路径
14     private ArrayList<Integer> onePath = new ArrayList<Integer>();
15     
16     // 返回所有的路径
17     public ArrayList<ArrayList<Integer>> FindAllPath(TreeNode root) {
18         if(root == null)
19             return allPaths;
20         
21         // 把当前结点加入到路径当中来
22         onePath.add(root.val);
23         
24         // 如果为叶子结点,则把onePath加入到allPaths当中
25         if(root.left == null && root.right == null){
26             allPaths.add(new ArrayList<Integer>(onePath));
27         }
28         
29         FindAllPath(root.left);
30         FindAllPath(root.right);
31         
32         // 这个地方可以通过画递归树来理解,无论叶子结点是左结点还是右结点,都会经过下面这一步,而且至关重要
33         onePath.remove(onePath.size() - 1);
34         return allPaths;
35     }
36     
37     public static void main(String[] args) {
38 
39     }
40 
41 }
42 
43 class TreeNode {
44     int val = 0;
45     TreeNode left = null;
46     TreeNode right = null;
47 
48     public TreeNode(int val) {
49         this.val = val;
50 
51     }
52 
53 }

 

转载于:https://www.cnblogs.com/wjf0/p/5873902.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值