【Leetcode】17.12: BiNode

这题我最开始想直接用递归和二叉树的左小,右边大的性质,快速得解。左子树和右子树分别看作一条链表,然后讲左子树接在右子树的上面,而左子树当中的最大元素始终比右子树的最小元素要小。没想到代码竟然无法编译通过,错误解答如下:

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

class Solution:
    def convertBiNode(self, root: TreeNode) -> TreeNode:
        #这个题目直接使用中序遍历就可以了,我的递归方法居然不好使..是简单题也是有原因的
        if root==None:
            return None
        else:
            node=self.convertBiNode(root.left)
            node_left=node
            while node!=None node.right!=None:
                node=node.right
            node.right=self.convertBiNode(root.right)
            root.right=node_left
            root.left=None

后来想到这题也就是简单难度的题目,只需要中序遍历inorder遍历就可以了,我醉了,,,这么简单。。最后用一个简单inoder遍历+一个数组储存得到的node变量,求解:

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

class Solution:
    def convertBiNode(self, root: TreeNode) -> TreeNode:
        new_node=TreeNode("0")
        cur=new_node
        ret=[]
        def DFS(root):
            if root==None:
                return None
            DFS(root.left)
            #引入中间变量
            ret.append(root.val)
            DFS(root.right)
        DFS(root)

        for i in ret:
            new_node.right=TreeNode(i)
            new_node=new_node.right
        return cur.right

由于比起单个inorder遍历,时间复杂度从n变成了2n(不用大O表示法),在leetcode上排名不突出。因此尝试只用一个DFS的方法,看看能不能使用参数传递

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值