-
Notifications
You must be signed in to change notification settings - Fork 1
/
BinaryTreePath.java
67 lines (60 loc) · 1.7 KB
/
BinaryTreePath.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.alg.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
*
* 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"]
*
*
* Solution 1:
* 1)start from the root node and traverse down its child
* 2)take one branch at a time for every traversed node and add the value of the node to
* the path string
* 3)when the next child node (on left side and right side) is null, the string is complete,
* else we just keep on appending the value of this node to the current path
*
*
* @author rbaral
*/
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
public class BinaryTreePath {
public static List<String> binaryTreePaths(TreeNode root) {
List<String> pathList = new ArrayList<String>();
if (root != null) {
performDFS(root, "", pathList);
}
return pathList;
}
static void performDFS(TreeNode root, String path, List<String> pathList) {
if (root.left == null && root.right == null) {
pathList.add(path + root.val);
}
if (root.left != null) {
performDFS(root.left, path + root.val + "->", pathList);
}
if (root.right != null) {
performDFS(root.right, path + root.val + "->", pathList);
}
}
public static void main(String args[]) {
}
}