题解 | 二叉树的前序遍历
二叉树的前序遍历
https://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
/**
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
object Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
fun preorderTraversal(root: TreeNode?): IntArray {
// write code here
val result = mutableListOf<Int>()
dfsPreOrder(root,result)
return result.toIntArray()
}
fun dfsPreOrder(root:TreeNode?,result:MutableList<Int>){
if(root==null)return
result.add(root.`val`)
dfsPreOrder(root.left,result)
dfsPreOrder(root.right,result)
}
}