樹-遞歸-面試題27. 二叉樹的鏡像

/**
 * 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 = root.right;
        root.right=tmpnode;
        //遞歸交換當前節點的 左子樹
        mirrorTree(root.left);
        //遞歸交換當前節點的 右子樹
        mirrorTree(root.right);
        return root;
    }
}

 參考博客鏈接:

https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/dong-hua-yan-shi-liang-chong-shi-xian-mian-shi-ti-/

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