首页 > 其他 > 详细

Leetcode: Binary Tree Paths

时间:2015-12-22 13:01:31      阅读:229      评论: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"]

 

 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     public List<String> binaryTreePaths(TreeNode root) {
12         List<String> res = new ArrayList<String>();
13         if (root == null) return res;
14         helper(root, res, "");
15         return res;
16     }
17     
18     public void helper(TreeNode root, List<String> res, String item) {
19         if (root.left == null && root.right == null) {
20             if (item.length() == 0) {
21                 res.add("" + root.val);
22             }
23             else {
24                 res.add(item + "->" + root.val);
25             }
26             return;
27         }
28         if (root.left != null) 
29             helper(root.left, res, item.length()==0? ""+root.val : item+"->"+root.val);
30         if (root.right != null)
31             helper(root.right, res, item.length()==0? ""+root.val : item+"->"+root.val);
32         
33     }
34 }

 

Leetcode: Binary Tree Paths

原文:http://www.cnblogs.com/EdwardLiu/p/5066289.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!