var result = [Int]() result.append(root.val) let leftResult = preorderTraversal(root.left) let rightResult = preorderTraversal(root.right) result.append(contentsOf: leftResult) result.append(contentsOf: rightResult) return result }
funcpreorderTraversal(_root: TreeNode?) -> [Int] { var res = [Int]() var cur = root var stack = [TreeNode]() while cur !==nil||!stack.isEmpty { while cur !=nil { res.append(cur!.val) stack.append(cur!) cur = cur?.left } cur = stack.popLast() cur = cur?.right } return res }
左右路入栈:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcpreorderTraversal(_root: TreeNode?) -> [Int] { guard root !==nilelse { return [] } var res = [Int]() var stack: [TreeNode] = [root!] while!stack.isEmpty { let cur = stack.popLast() res.append(cur!.val) iflet right = cur?.right { stack.append(right) } iflet left = cur?.left { stack.append(left) } } return res }