funcinorderTravelsal(_root: TreeNode?) -> [Int] { guardlet root = root else { return [] } var result = [Int]()
let leftList = inorderTravelsal(root.left) let rightList = inorderTravelsal(root.right) result.append(contentsOf: leftList) result.append(root.val) result.append(contentsOf: rightList) return result }
遍历法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcinorderTraversal(_root: TreeNode?) -> [Int] { var res = [Int]() var stack = [TreeNode]() var cur = root while cur !==nil||!stack.isEmpty { // 遍历当前节点的左子树,并入栈遍历到的节点,直到左节点为空 while cur !==nil { stack.append(cur!) cur = cur?.left } // 取出栈顶节点,输出该节点,并遍历该节点的右子树 cur = stack.popLast() res.append(cur!.val) cur = cur?.right } return res }