Python modified in-order traverse


  • 0
    C

    Easy to understand.

    class Solution(object):
        def convertBST(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            def visit(node, ans):
                if node is None:
                    return
                
                visit(node.right, ans)
                if ans[0] is None:
                    ans[0] = node.val
                else:
                    node.val = ans[0] = node.val+ans[0]
                    
                visit(node.left, ans)
                
            visit(root, [None])
            return root
    

    Or used a variable to store the node visited.

    class Solution(object):
        def convertBST(self, root):
            def visit(node, pre):
                if node is None:
                    return
                
                visit(node.right, pre)
                if pre[0] is not None:
                    node.val += pre[0].val
                    
                pre[0] = node
                    
                visit(node.left, pre)
                
            visit(root, [None])
            return root
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.