• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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 /**
 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 }

 

posted @ 2015-12-22 12:44  neverlandly  阅读(275)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3