257 Binary Tree Paths

257. Binary Tree Paths

1. Question

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

2. Implementation

(1) DFS

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();        
        getTreePaths(root, "", res);
        return res;
    }

    public void getTreePaths(TreeNode node, String curPath, List<String> res) {
        if (node == null) {
            return;
        }

        if (node.left == null && node.right == null) {
            res.add(curPath + node.val);
            return;
        }

        getTreePaths(node.left, curPath + node.val + "->", res);
        getTreePaths(node.right, curPath + node.val + "->", res);
    }
}

(2) BFS

3. Time & Space Complexity

(1) DFS: 时间复杂度: O(n), 空间复杂度: O(h)

(2) BFS: 时间复杂度: O(n), 空间复杂度: O(w)

Last updated

Was this helpful?