二叉樹的鏡像題解

題目:

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

例如輸入:

     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 tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        mirrorTree(root.left);
        mirrorTree(root.right);

        return root;
    }
}

 

 

 

 

 

 

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