257. Binary Tree Paths

Description

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

tree

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.

Solution

DFS

最常规的recur写法。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List binaryTreePaths(TreeNode root) {
        List paths = new LinkedList<>();
        if (root == null) {
            return paths;
        }
        
        dfs(root, new StringBuilder(), paths);
        return paths;
    }
    
    private void dfs(TreeNode root, StringBuilder sb, List paths) {
        int originalLen = sb.length();  // keep original length
        sb.append(originalLen > 0 ? "->" : "").append(root.val);
        
        if (root.left == null && root.right == null) {
            paths.add(sb.toString());
        } else {
            if (root.left != null) {
                dfs(root.left, sb, paths);
            }
            
            if (root.right != null) {
                dfs(root.right, sb, paths);
            }
        }
        
        sb.setLength(originalLen);
    }
}

Without helper function

下面这种写法超简洁,但缺点是String相加的cost。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List binaryTreePaths(TreeNode root) {
        List paths = new LinkedList<>();
        if (root == null) {
            return paths;
        }
        
        if (root.left == null && root.right == null) {
            paths.add(String.valueOf(root.val));
            return paths;
        }
        
        for (String path : binaryTreePaths(root.left)) {
            paths.add(root.val + "->" + path);
        }
        
        for (String path : binaryTreePaths(root.right)) {
            paths.add(root.val + "->" + path);
        }
        
        return paths;
    }
}

你可能感兴趣的:(257. Binary Tree Paths)