二叉树的镜像
2023-09-11 14:15:14 时间
二叉树的镜像
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
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]
限制:
0 <= 节点个数 <= 1000
示例代码1:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mirrorTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
tmp = root.left
root.left = self.mirrorTree(root.right)
root.right = self.mirrorTree(tmp)
return root
示例代码2:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mirrorTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
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
相关文章
- 二叉树的遍历、求深与还原
- LeetCode222之完全二叉树的节点个数(相关话题:完全二叉树)
- LeetCode426之公共祖先(相关话题:二叉树后序,Set和Map的应用)
- 107、【树与二叉树】leetcode ——236. 二叉树的最近公共祖先:回溯法(C++版本)
- 【数据结构/二叉树/公共祖先问题】题解+详细备注(共2题)
- [LeetCode] 1028. Recover a Tree From Preorder Traversal 从先序遍历还原二叉树
- [LintCode] Invert Binary Tree 翻转二叉树
- [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和后序遍历建立二叉树
- LeetCode二叉树路径总和
- LeetCode二叉树中序遍历
- Python蓝桥杯训练:基本数据结构 [二叉树] 中
- 已知二叉树前序和中序,求后序