1. 程式人生 > 實用技巧 >go開發目錄配置-go mod

go開發目錄配置-go mod

劍指 Offer 27. 二叉樹的映象

地址:劍指 Offer 27. 二叉樹的映象

問題描述:

請完成一個函式,輸入一個二叉樹,該函式輸出它的映象。

例如輸入:

4

/
2 7
/ \ /
1 3 6 9
映象輸出:

4

/
7 2
/ \ /
9 6 3 1

示例 1:

輸入:root = [4,2,7,1,3,6,9]
輸出:[4,7,2,9,6,3,1]

限制:

0 <= 節點個數 <= 1000

/**
 * Definition for a binary tree node.
 * class TreeNode(var _value: Int) {
 *   var value: Int = _value
 *   var left: TreeNode = null
 *   var right: TreeNode = null
 * }
 */
object Solution {
    def mirrorTree(root: TreeNode): TreeNode = {
        if (root == null) return root
        val left = mirrorTree(root.right)
        val right = mirrorTree(root.left)
        root.left = left
        root.right = right
        return root
    }
}
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func mirrorTree(root *TreeNode) *TreeNode {
    if root == nil {return root}
    root.Left, root.Right = mirrorTree(root.Right), mirrorTree(root.Left)
    return root 
}