Created
August 10, 2019 23:42
-
-
Save wszdwp/076305b4eb105fbd9db64de8418375e4 to your computer and use it in GitHub Desktop.
non-recur and recur for bst paths
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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