美文网首页
LeetCode-Golang之【144. 二叉树的前序遍历】

LeetCode-Golang之【144. 二叉树的前序遍历】

作者: StevenChu1125 | 来源:发表于2020-12-05 22:10 被阅读0次

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

题解

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func preorderTraversal(root *TreeNode) []int {
    var res []int
    preOrder(root,&res)
    return res
}

func preOrder(root *TreeNode,res *[]int){
    if root !=nil{
        *res=append(*res, root.Val)
        if root.Left != nil {
            preOrder(root.Left,res)
        }
        if root.Right !=nil {
            preOrder(root.Right,res)
        }
    } 
}

相关文章

网友评论

      本文标题:LeetCode-Golang之【144. 二叉树的前序遍历】

      本文链接:https://www.haomeiwen.com/subject/yqdnwktx.html