257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

 

   1
 /   \
2     3
 \
  5

 

All root-to-leaf paths are:

["1->2->5", "1->3"]
题目含义:找到所有从根到叶子加点的路径
 1      public void appendChildren(TreeNode root,String curPath,List<String> answer) {
 2         if (root == null) return;
 3         if (root.left== null && root.right==null) answer.add(curPath+root.val);
 4         if (root.left!=null) appendChildren(root.left,curPath+root.val+"->",answer);
 5         if (root.right!=null) appendChildren(root.right,curPath+root.val+"->",answer);
 6     }   
 7     
 8     public List<String> binaryTreePaths(TreeNode root) {
 9          if(root == null) return new ArrayList<String>();
10         List<String> result = new ArrayList<>();
11         appendChildren(root,"",result);   
12         return result;
13     }

 

posted @ 2017-10-24 13:32  daniel456  阅读(109)  评论(0编辑  收藏  举报