1. 程式人生 > 其它 >【題解】Loj6053 簡單的函式

【題解】Loj6053 簡單的函式

話不多說,先上題目

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

例如輸入:

     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]

來源:力扣(LeetCode)


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root == null) {
            return root;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        TreeNode temp = left;
        left = right;
        right = temp;
        root.right = mirrorTree(right);
        root.left = mirrorTree(left);
        return root;
    }
}

本文來自部落格園,作者:金木研King,轉載請註明原文連結:https://www.cnblogs.com/jinzlblog/p/15126152.html