Leetcode sum of left subtree getting error - python

The below code works fine for sample input but provides the wrong answer for
[1,2,3,4,5]
excepted answer:4
program output: 6
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root: return 0
sum=0
a=deque([root])
while a:
for i in range(len(a)):
node=a.popleft()
if node.left:
sum+=node.left.val
a.(node.left)
if node.right:
a.append(node.right)
return sum

Related

Count Nodes Equal to Average of Subtree

I'm the beginner for python,and I always feel confused about binary tree when I practise in leetcode.
Here is my code:
from typing import Optional
#Definition for a binary tree node.(This is given by leetcode)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
ans = 0
def traverse(node):
if node is None:
return (0,0)
left = traverse(node.left)
right = traverse(node.right)
total = left[0] + right[0] + node.val
count = left[1] + right[1] +1
if total // count == node.val:
nonlocal ans
ans += 1
return (total, count)
traverse(root)
return ans
root = [4,8,5,0,1,None,6]
a = Solution()
print(a.averageOfSubtree(root))
The TreeNode definition is given by leetcode, and I just copy down and run on my vscode, however, it hint an error:AttributeError: 'list' object has no attribute 'left'
How can I modify it?

Understanding overriding in in-order tree traversal

I am looking to return the k-th element of a binary tree and came up with this solution:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
if not root:
return None
out = []
return self.Search(root,k,out)[k-1]
def Search(self,root,k,out):
if root:
# iterate over the tree using DFS, and after the last iteration return the sorted list "out"
self.Search(root.left,k,out)
self.Search(root.right,k,out)
out.append(root.val)
return sorted(out)
My question is: Why can't I return sorted(out)[k-1] in the Search method? I have to return the sorted list to the kthSmallest method and then search for the k-th entry and I don't understand why.

Check if a Binary Tree is Balanced or not

I tried to solve this question in LeetCode, even though my solution was right, one particular test case has failed.
My Code :
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
#height,flag = self.dfs(root)
return self.dfs(root)[1]
def dfs(self,node,isTreeBalanced=True):
if node is None or not isTreeBalanced:
return 0,isTreeBalanced
leftHeight , isTreeBalanced = self.dfs(node.left,isTreeBalanced)
rightHeight, isTreeBalanaced = self.dfs(node.right,isTreeBalanced)
print(abs(leftHeight-rightHeight))
if abs(leftHeight - rightHeight) > 1:
isTreeBalanced = False
return max(leftHeight,rightHeight)+1 , isTreeBalanced
Test Case Input for which my Code failed:
[1,2,3,4,5,null,6,7,null,null,null,null,8]
Leetcode question : Check if the Tree is Balanced or not
Can anyone help in identifying the issue? Is there any edge case I am missing ?
Your code is correct and you have not missed any testcase, it is just that you have misspelled the isTreeBalanced as isTreeBalanaced which is why you were getting the testcase failed which was having only nodes on left and just one node on right.
Although I solved this entire question and here is my code for the above question:
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
self.Balanced = True
if not root:
return self.Balanced
self.maxDepth(root)
return self.Balanced
def maxDepth(self, root):
if not root:
return 0
else:
ldepth = self.maxDepth(root.left)
rdepth = self.maxDepth(root.right)
if abs(ldepth - rdepth) >= 2:
self.Balanced = False
return max(ldepth, rdepth) + 1
Time Complexity : O(N)
Space Complexity : O(N) (For call stack)

Python recursion didn't give correct result for "sum of left leaves"

I wrote a code for the leetcode problem "108. Sum of Left Leaves" using recursion. It didn't give me the expected result.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
ans = 0
if root.left and not root.left.left and not root.left.right:
ans += root.left.val
self.sumOfLeftLeaves(root.left)
self.sumOfLeftLeaves(root.right)
return ans
When the input is
[3,9,20,null,null,15,7]
I expected a 24 to be returned, but the code only gave me 9
You aren't adding the results of the leaves below the root. You need this:
class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
ans = 0
if root.left and not root.left.left and not root.left.right:
ans += root.left.val
ans += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
return ans

Would this function for checking if a BST(Binary Search Tree ) Is valid work Python

So this is my code below, my thought process is that if the smallest value in the tree is less than the root and the largest value in the tree is greater than the root it should check if the BST is valid
def min(self):
while self.left:
self.root = self.left
return self.root
def max(self):
while self.right:
self.root = self.right
return self.value
def valid(self):
min = min(self.left)
max = max(self.right)
if self.root > min and self.root < max:
return True
Don't reuse the names min and max. They already refer to built-in functions.
Your min and max functions change the tree, by changing self.root.
You should be validating that the values of the left and right child nodes are correct relative to the parent node, then validating that each of the BSTs rooted at those child nodes is itself valid.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def valid(self):
if self.left and self.left.value > self.value:
return False
if self.right and self.right.value < self.value:
return False
return all(node.valid() for node in (self.left, self.right) if node)

Categories

Resources