码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-09-14 23:07:40      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:

 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 }

 

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

标签:

原文地址:http://www.cnblogs.com/wjf0/p/5873902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!