二叉树的镜像

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

 1 # -*- coding:utf-8 -*-
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 class Solution:
 8     # 返回镜像树的根节点
 9     def Mirror(self, root):
10         if root == None:
11             return None
12         if root.left != None and root.right != None:
13             temp = TreeNode(root.val)
14             temp.left = root.left
15             root.left = self.Mirror(root.right)
16             root.right = self.Mirror(temp.left)
17         elif root.left == None and root.right != None:
18             root.left = self.Mirror(root.right)
19             root.right = None
20         elif root.right == None and root.left != None:
21             root.right = self.Mirror(root.left)
22             root.left = None
23         return root
24         # write code here

 

Java版,leetcode地址

 1 class Solution {
 2     public TreeNode mirrorTree(TreeNode root) {
 3         if (root == null) {
 4             return null;
 5         }
 6         if (root.left != null && root.right != null) {
 7             TreeNode tempNode = new TreeNode(0);
 8             tempNode.left = root.left;
 9             root.left = mirrorTree(root.right);
10             root.right = mirrorTree(tempNode.left);
11         } else if (root.left != null && root.right == null) {
12             root.right = mirrorTree(root.left);
13             root.left = null;
14         } else if (root.left == null && root.right != null) {
15             root.left = mirrorTree(root.right);
16             root.right = null;
17         }
18         return root;
19     }
20 }

 

posted on 2019-06-12 22:15  Sempron2800+  阅读(115)  评论(0编辑  收藏  举报