天天看點

劍指 Offer 27. 二叉樹的鏡像

請完成一個函數,輸入一個二叉樹,該函數輸出它的鏡像。

例如輸入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9
           

鏡像輸出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

           

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof

著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode copyRoot = new TreeNode(root.val);
        copyRoot.left = mirrorTree(root.right);
        copyRoot.right = mirrorTree(root.left);
        return copyRoot;
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

           

心之所向,素履以往 生如逆旅,一葦以航