[LeetCode] 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"]
Thought process:
DFS.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | /** * 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; } String path = Integer.toString(root.val); binaryTreePaths(root, path, paths); return paths; } private void binaryTreePaths(TreeNode node, String path, List<String> paths) { if (node.left == null && node.right == null) { paths.add(path); return; } if (node.left != null) { binaryTreePaths(node.left, path + "->" + node.left.val, paths); } if (node.right != null) { binaryTreePaths(node.right, path + "->" + node.right.val, paths); } } } |
Time complexity: O(n).
Comments
Post a Comment