树-树的对称与镜像问题

link:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
describe:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:

     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]
class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        stack=[root]
        while stack:
            node=stack.pop()
            if node.left:stack.append(node.left)
            if node.right:stack.append(node.right)
            node.left,node.right = node.right,node.left
        return root


方式二:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        root.left,root.right = self.mirrorTree(root.right),self.mirrorTree(root.left)
        return root
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / 
  2   2
 /  / 
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / 
  2   2
      
   3    3

 

示例 1:

输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        def recur(L, R):
            if not L and not R: return True
            if not L or not R or L.val != R.val: return False
            return recur(L.left, R.right) and recur(L.right, R.left)
        return recur(root.left, root.right) 
好好学习,天天向上
原文地址:https://www.cnblogs.com/topass123/p/13369915.html