April 21, 2019

257. Binary Tree Paths

257. Binary Tree Paths

法1. DFS Recursion (Divide and Conquer)

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

法2. DFS Recursive (Traverse)

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<>();
        binaryTreePaths(root, "", paths);
        return paths;
    }
    
    private void binaryTreePaths(TreeNode root, String path, List<String> paths) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            paths.add(path + root.val);
        }
        binaryTreePaths(root.left, path + root.val + "->", paths);
        binaryTreePaths(root.right, path + root.val + "->", paths);

    }
}
comments powered by Disqus