File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ // recursion
12class Solution {
23 fun tree2str (root : TreeNode ? ): String {
34 val res = StringBuilder ()
@@ -22,3 +23,39 @@ class Solution {
2223 return res.toString()
2324 }
2425}
26+
27+ // iterative
28+ class Solution {
29+ fun tree2str (root : TreeNode ? ): String {
30+ root? : return " "
31+
32+ val res = StringBuilder ()
33+ val stack = LinkedList <TreeNode ?>().apply { addLast(root) }
34+ val visited = HashSet <TreeNode ?>()
35+
36+ while (stack.isNotEmpty()) {
37+ val cur = stack.peekLast()
38+
39+ if (cur in visited) {
40+ stack.removeLast()
41+ res.append(" )" )
42+ } else {
43+ visited.add(cur)
44+ res.append(" (" )
45+ res.append(cur?.`val `)
46+
47+ if (cur?.left == null && cur?.right != null )
48+ res.append(" ()" )
49+
50+ if (cur?.right != null )
51+ stack.addLast(cur?.right)
52+ if (cur?.left != null )
53+ stack.addLast(cur?.left)
54+ }
55+ }
56+
57+ res.deleteCharAt(0 )
58+ res.deleteCharAt(res.lastIndex)
59+ return res.toString()
60+ }
61+ }
You can’t perform that action at this time.
0 commit comments