Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created August 10, 2019 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wszdwp/076305b4eb105fbd9db64de8418375e4 to your computer and use it in GitHub Desktop.
Save wszdwp/076305b4eb105fbd9db64de8418375e4 to your computer and use it in GitHub Desktop.
non-recur and recur for bst paths
public List<String> binaryTreePaths(TreeNode root) {
//List<List<Integer>> ans = new ArrayList<>();
// dfs(root, new ArrayList<>(), ans);
// return formatAns(ans);
List<String> ans = new ArrayList<>();
dfsIter(root, ans);
return ans;
}
private void dfsIter(TreeNode root, List<String> ans) {
if (root == null) return;
TreeNode p = root;
Stack<String> path = new Stack<>();
Stack<TreeNode> stk = new Stack<>();
stk.push(p);
path.push(String.valueOf(p.val));
while (!stk.isEmpty()) {
TreeNode cur = stk.pop();
String tempPath = path.pop();
if (cur.left == null && cur.right == null) {
ans.add(new String(tempPath));
}
if (cur.right != null) {
stk.push(cur.right);
path.push(tempPath + "->" + cur.right.val);
}
if (cur.left != null) {
stk.push(cur.left);
path.push(tempPath + "->" + cur.left.val);
}
}
}
private List<Integer> getPath(Stack<TreeNode> stk) {
Stack<TreeNode> copy = new Stack<>();
List<Integer> ans = new ArrayList<>();
while (!stk.isEmpty()) {
copy.push(stk.pop());
}
while (!copy.isEmpty()) {
TreeNode nd = copy.pop();
stk.push(nd);
ans.add(nd.val);
}
return ans;
}
private void dfs(TreeNode root, List<Integer> cur, List<List<Integer>> ans) {
if (root == null) return;
cur.add(root.val);
if (root.left == null && root.right == null) ans.add(new ArrayList<>(cur));
dfs(root.left, cur, ans);
dfs(root.right, cur, ans);
cur.remove(cur.size() - 1);
}
private List<String> formatAns(List<List<Integer>> ans) {
List<String> res = new ArrayList<>();
for (List<Integer> one : ans) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < one.size(); i++) {
sb.append(one.get(i));
if (i != one.size() - 1) sb.append("->");
}
res.add(sb.toString());
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment