zoukankan      html  css  js  c++  java
  • 【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的方法,看看能不能使用参数传递

  • 相关阅读:
    HDU2586 How far away?(tarjan的LCA)
    You Raise Me Up
    POJ2891 Strange Way to Express Integers(中国剩余定理)
    POJ2142 The Balance(扩展欧几里得)
    HDU 1166模仿大牛写的线段树
    NetWord Dinic
    HDU 1754 线段树裸题
    hdu1394 Minimum Inversion Number
    hdu2795 Billboard
    【完全版】线段树
  • 原文地址:https://www.cnblogs.com/geeksongs/p/14626175.html
Copyright © 2011-2022 走看看