当前位置: 首页 > 后端技术 > Python

力扣-0114.二叉树扩展为链表[Python][Go]

时间:2023-03-26 13:47:29 Python

问题LeetCode给定一棵二叉树,将其展平为链表。例如,给定以下树:1/\25/\\346展平的树应该是这样的:1\2\3\4\5\6链表就地。比如给定一棵二叉树1/\25/\\346,将其展开为:1\2\3\4\5\6递归思路1.先将左右子树展平成一个链表2.然后将左子树树作为新的右子树3.最后将原来的右子树连接到当前右子树的末尾Python3代码#Definitionforabinarytreenode.#classTreeNode:#def__init__(self,val=0,left=None,right=None):#self.val=val#self.left=left#self.right=rightclass解决方案:defflatten(self,root:TreeNode)->None:"""不要返回任何东西,就地修改根。"""ifnotroot:return#递归调用self.flatten(root.left)self.flatten(root.right)#后序遍历:left-right-root#左右子树被压平成链表left=TreeNode()left=root.leftright=TreeNode()right=root.right#左子树作为右子树root.left=Noneroot.right=left#原来的右子树连接到当前右子树的末端p=TreeNode()p=root#找到当前右子树的末端whilep.right!=None:p=p.rightp.right=rightGo代码/***二叉树节点的定义。*typeTreeNodestruct{*Valint*Left*TreeNode*Right*TreeNode*}*/funcflatten(root*TreeNode){ifroot==nil{return}//递归调用flatten(root.Left)flatten(root.Right)//后序遍历:left-right-root//将左右子树展平成链表varleft=new(TreeNode)left=root.Leftvarright=new(TreeNode)right=root.Right//左子树作为右子树root.Left=nilroot.Right=left//原来的右子树连接到当前右子树的末尾varp=new(TreeNode)p=root//找到当前右子树的末尾for{ifp.Right==nil{break}p=p.Right}p.Right=right}GitHublinkPythonGoProblemLeetCode给定一棵二叉树,就地将其展平为链表。例如,给定以下树:1/\25/\\346扁平化的树应该是这样的:1\2\3\4\5\6二叉树,就地展开成单链表比如给定一棵二叉树1/\25/\\346,将其展开为:1\2\3\4\5\6递归思路1.先将左右子树展平成一个链表2.然后将左子树树作为新的右子树3.最后将原来的右子树连接到当前右子树的末尾Python3代码#Definitionforabinarytreenode.#classTreeNode:#def__init__(self,val=0,left=None,right=None):#self.val=val#self.left=left#self.right=rightclass解决方案:defflatten(self,root:TreeNode)->None:"""不要返回任何东西,就地修改根。"""ifnotroot:return#递归调用self.flatten(root.left)self.flatten(root.right)#后序遍历:left-right-root#左右子树被压平成链表left=TreeNode()left=root.leftright=TreeNode()right=root.right#左子树作为右子树root.left=Noneroot.right=left#原来的右子树连接到当前右子树的末端p=TreeNode()p=root#找到当前右子树的末端whilep.right!=None:p=p.rightp.right=rightGo代码/***二叉树节点的定义。*typeTreeNodestruct{*Valint*Left*TreeNode*Right*TreeNode*}*/funcflatten(root*TreeNode){ifroot==nil{return}//递归调用flatten(root.Left)flatten(root.Right)//后序遍历:left-right-root//将左右子树展平成链表varleft=new(TreeNode)left=root.Leftvarright=new(TreeNode)right=root.Right//左子树作为右子树root.Left=nilroot.Right=left//原右子树连接到当前右子树的末尾varp=new(TreeNode)p=root//查找当前右子树的末尾{ifp.Right==nil{break}p=p.Right}p.Right=right}GitHublinkPythonGo