classTreeNode(var value: Int) { var left: TreeNode? = null var right: TreeNode? = null }
funpostorder(root: TreeNode?) { val stack: LinkList = LinkedList<TreeNode>() var cur = root var last = null while (cur != null || !stack.isEmpty()) { // 左节点先入栈 while (cur != null) { stack.addFirst(cur) // 第一次访问 cur = cur.left } val top = stack.peekFirst() // 第二次访问 if (top.right == null || top.right == last) { // 第三次访问 visit(top) last = top stack.removeFirst() } else { cur = top.right } } }
val neighbors = adjList[vertex] if (neighbors != null) { for (neighbor in neighbors) { if (!visited.contains(neighbor)) { dfsHelper(neighbor, visited) } } } } }