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

一刷
题解:思路很简单,用dfs。但是如何解决stringbuilder append之后抹去时的长度问题。于是决定不用object而是用变量string.在函数中并不去改变这个变量

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root==null) return res;
        dfs(root, res, "");
        return res;
    }
    
    private void dfs(TreeNode root, List<String> res, String path){
        if(root.left==null && root.right == null) res.add(path + root.val);
        if(root.left!=null) dfs(root.left, res, path + root.val + "->");
        if(root.right!=null) dfs(root.right, res, path + root.val + "->");
    }
}

二刷
思路同上:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null) return res;
        dfs("", res, root);
        return res;
    }
    
    private void dfs(String path, List<String> res, TreeNode root){
        if(root == null) return;
        if(root.left == null && root.right == null){
            res.add(path + root.val);
            return;
        }
        else{
            dfs(path + root.val + "->", res, root.left);
            dfs(path + root.val + "->", res, root.right);
        }
    }
}

三刷

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null) return res;
        helper(root, "", res);
        return res;
    }
    
    private void helper(TreeNode root, String s, List<String> res){
        if(root.left==null && root.right == null){
            res.add(s + root.val);
            return;
        }
        if(root.left!=null){
            String cur = s + root.val + "->";
            helper(root.left, cur, res);
        } 
        if(root.right!=null){
            String cur = s + root.val + "->";
            helper(root.right, cur, res);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容