第18题——二叉树的镜像

177 阅读1分钟

题目:

操作给定的二叉树,将其变换为源二叉树的镜像

二叉树的镜像定义:源二叉树 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	镜像二叉树
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

思路:

递归的交换二叉树的左右节点

Python

from PrintTreeLayer import PrintTreeLayer
class Mirror:
    def Mirror(self, root):
        if root:
            node = root.left
            root.left = root.right
            root.right = node
            if root.left:
                self.Mirror(root.left)
            if root.right:
                self.Mirror(root.right)
        return root
if __name__ == '__main__':
    test = Mirror()
    array = [8, 6, 10, 5, 7, 9, 11]
    p = PrintTreeLayer()
    root = p.arrayToTree(array, 0)
    p.printTreeLayer(root)
    node = test.Mirror(root)
    print()
    p.printTreeLayer(node)

结果:

8 6 10 5 7 9 11 
8 10 6 11 9 7 5 
Process finished with exit code 0

Java

package nowcoder;

public class S18_Mirror {
    public TreeNode Mirror(TreeNode root){
        TreeNode temp = null;
        if (root != null){
            temp = root.left;
            root.left = root.right;
            root.right = temp;
            if (root.left != null)
                Mirror(root.left);
            if (root.right != null)
                Mirror(root.right);
        }
        return root;
    }
    public static void main(String[] args){
        S18_Mirror s18 = new S18_Mirror();
        Integer[] array = {8, 6, 10, 5, 7, 9, 11};
        PrintTreeLayer p = new PrintTreeLayer();
        TreeNode root = p.arrayToTree(array, 0);
        p.printTreeLayer(root);
        System.out.println();
        p.printTreeLayer(s18.Mirror(root));
    }
}