码迷,mamicode.com
首页 > 编程语言 > 详细

257. Binary Tree Paths java solutions

时间:2016-06-24 19:04:12      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

 
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     List<String> ans = new ArrayList<String>();
12     public List<String> binaryTreePaths(TreeNode root) {
13         if(root == null) return ans;
14         String tmp = "" + root.val;
15         DFS(ans,root,tmp);
16         return ans;
17     }
18     
19     public void DFS(List<String> ans, TreeNode node, String tmp){
20         if(node.left == null && node.right == null){
21             ans.add(tmp);
22             return;
23         }
24         if(node.left != null) DFS(ans,node.left,tmp+"->"+node.left.val);
25         if(node.right != null) DFS(ans,node.right,tmp+"->"+node.right.val);
26     }
27 }

用递归即可。

257. Binary Tree Paths java solutions

标签:

原文地址:http://www.cnblogs.com/guoguolan/p/5614950.html

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