funcpostorderTraversal2(_root: TreeNode?) -> [Int] { var result = [Int]() var stack = [TreeNode]() var cur = root var flag: TreeNode? =nil
while cur !=nil||!stack.isEmpty { while cur !=nil { stack.append(cur!) cur = cur?.left }
cur = stack.removeLast() if cur?.right ===nil|| cur?.right === flag { result.append(cur!.val) flag = cur cur =nil } else { stack.append(cur!) //右子树不为空,即上面出栈后又继续入栈,在更新cur值,再去从头循环 cur = cur?.right } }
return result }
遍历2: 左右子树均入栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcpostorderTraversal3(_root: TreeNode?) -> [Int] { guardlet root = root else { return [] } var result = [Int]() var stack = [root] while!stack.isEmpty { let cur = stack.removeLast() result.insert(cur.val, at: 0) // 逆序添加到结果数组中 // 先添加左子树,后添加右子树,这样取出的时候就是先取出右子树,逆序添加到结果数组中时就是左-右-中 iflet left = cur.left { stack.append(left) } iflet right = cur.right { stack.append(right) } } return result }