反转二叉树

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12917797.html

反转二叉树(48min)

题目链接:https://leetcode-cn.com/problems/invert-binary-tree/

翻转一棵二叉树。

示例:

输入:

4
/
2 7
/ /
1 3 6 9
输出:

4
/
7 2
/ /
9 6 3 1

题解:

        思路:递归思想。

                 1.先取根的左右子树,交换左右子树。

                 2.在交换左右子树的左右子树。

代码如下:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null)
             return root;
        TreeNode temp=root.right;
        root.right=root.left;
        root.left=temp;
        TreeNode right=invertTree(root.left);
        TreeNode left=invertTree(root.right);
        return root;
        
    }
}

 这题也适合反转二叉树的镜像,镜像即二叉树的左右子树的左右子树全都交换位置。

题目链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:

     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]

原文地址:https://www.cnblogs.com/ping2yingshi/p/12917797.html