树-递归-面试题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-/

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