算法 |《劍指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.
 * 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 null;
        TreeNode tmpNode = root.left;
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(tmpNode);
        // TreeNode left = mirrorTree(root.left);
        // TreeNode right = mirrorTree(root.right);
        // root.left = right;
        // root.right = left;
        return root;

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章