首页 > 其他 > 详细

Leetcode 257

时间:2018-05-13 14:58:39      阅读:209      评论:0      收藏:0      [点我收藏+]

 

 

 

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<String> res = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        if(root == null) return res;
        StringBuilder str = new StringBuilder();
        dfs(root, str.append(root.val));
        return res;
    }
    void dfs(TreeNode node, StringBuilder str){
         if(node.left==null  && node.right==null){
             res.add(str.toString());
           
        }
        //node is not null
        
        if(node.left != null){
            str.append("->");
            str.append(node.left.val);
            //Integer num = 
            dfs(node.left, str);
            str.setLength(str.length() - 2 - (String.valueOf(node.left.val).length() ));
        }
         if(node.right != null){
            str.append("->");
            str.append(node.right.val);
            dfs(node.right, str);
            str.setLength(str.length() - 2 - (String.valueOf(node.right.val).length() ));
        }
        
       
        
        
    }
}

 

Leetcode 257

原文:https://www.cnblogs.com/stiles/p/leetcode257.html

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