本文主要是介绍Study Plan For Algorithms - Part21,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 二叉树的镜像
输入一个二叉树,输出它的镜像。
方法一:
class TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightdef mirrorTree(root):if not root:return Nonetemp, left, right = root.right, root.left, root.rightroot.left = mirrorTree(right)root.right = mirrorTree(temp)return root
方法二:
class TreeNode:def __init__(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightdef mirrorTree(root):if not root:return Nonestack = [root]while stack:node = stack.pop()if node.left:stack.append(node.left)if node.right:stack.append(node.right)temp = node.leftnode.left = node.rightnode.right = tempreturn root
这篇关于Study Plan For Algorithms - Part21的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!