Skip to content

Commit 817ea16

Browse files
committed
Java solution 257 & 258
1 parent aef77bc commit 817ea16

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

java/_257BinaryTreePaths.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.List;
2+
3+
import javax.management.relation.RelationTypeSupport;
4+
import javax.swing.tree.TreeNode;
5+
6+
/**
7+
* Given a binary tree, return all root-to-leaf paths.
8+
*
9+
* For example, given the following binary tree:
10+
*
11+
* 1
12+
* / \
13+
* 2 3
14+
* \
15+
* 5
16+
* All root-to-leaf paths are:
17+
*
18+
* ["1->2->5", "1->3"]
19+
*/
20+
21+
public class _257BinaryTreePaths {
22+
public List<String> binaryTreePaths(TreeNode root) {
23+
List<String> result = new ArrayList<>();
24+
if (root != null) {
25+
search(root, "", result);
26+
}
27+
return result;
28+
}
29+
30+
public void search(TreeNode node, String path, List<String> result) {
31+
if (node.left == null && node.right == null) {
32+
result.add(path + node.val);
33+
}
34+
if (node.left != null) {
35+
search(node.left, path + node.val + "->", result);
36+
}
37+
if (node.right != null) {
38+
search(node.right, path + node.val + "->", result);
39+
}
40+
}
41+
}

java/_258AddDigits.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
3+
*
4+
* For example:
5+
*
6+
* Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
7+
*
8+
* Follow up:
9+
* Could you do it without any loop/recursion in O(1) runtime?
10+
*/
11+
public class _258AddDigits {
12+
public int addDigits(int num) {
13+
int result = num % 9;
14+
return (result != 0 || num == 0) ? result : 9;
15+
}
16+
}

0 commit comments

Comments
 (0)