dimanche 31 janvier 2021

python if else return confusion, leetcode 669

Leetcode 669. Input: root = [1,0,2], low = 1, high = 2.

This code got error:

'Nonetype' object has no attribute 'val'

if not root will return, so anything passes this should be not None, which has a val.

def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
    def dfs(root):
        if not root:
            return None
        if root.val < low:         
            root = dfs(root.right)
        if root.val > high:
            root = dfs(root.left)  
        if root.val >= low and root.val <= high:
            root.left = dfs(root.left)
            root.right = dfs(root.right)
        return root            
    return dfs(root)

But the following works:

def trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:
    def dfs(root):
        if not root:
            return None
        elif root.val < low:            # OR if root.val < low
            root = dfs(root.right)
        elif root.val > high:
            root = dfs(root.left)  
        else:
            root.left = dfs(root.left)
            root.right = dfs(root.right)
        return root            
    return dfs(root)

I am confused why the first doesn't work. I think the ifs are mutually exclusive, so it will reach the return in the first if or through any of the last three to the end.

Aucun commentaire:

Enregistrer un commentaire