递归
fun inorderTraversal1(root: TreeNode?): List<Int> {
val l = ArrayList<Int>()
inorder(root, l)
return l
}
fun inorder(root: TreeNode?, l: ArrayList<Int>) {
if (root == null) return
inorder(root.left, l)
l.add(root.`val`)
inorder(root.right, l)
}
迭代
fun inorderTraversal(root: TreeNode?): List<Int> {
// 开栈
var rt = root
val stk = LinkedList<TreeNode>()
val l = ArrayList<Int>()
while (rt != null || stk.isNotEmpty()) {
rt = if (rt != null) {
stk.push(rt)
rt.left
} else {
// 到了最左边了左儿子
// 左儿子为空
// 弹出自己
val cur = stk.pop()
l.add(cur.`val`)
cur.right
}
}
return l
}
感觉递归好理解一些,迭代研究了好久才稍微明白一些。