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?
Related
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
I am trying to solve a problem that requires finding the minimum depth of a binary tree. I can't seem to find the error. Any advice would be of great help.
# 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 minDepth(self, root: TreeNode) -> int:
if not root:
return 0
queue = []
queue = collections.deque(queue)
queue.append(root)
depth = 0
while len(queue) != 0:
numberOfNodes = len(queue)
while numberOfNodes > 0:
currentNode = queue.popleft()
if not currentNode and not currentNode:
depth += 1
return depth
if currentNode.left:
queue.append(currentNode.left)
if currentNode.right:
queue.append(currentNode.right)
numberOfNodes -= 1
depth += 1
return depth
I think I found the slight error. In place of :
if not currentNode and not currentNode:
depth += 1
return depth
Maybe, it should be this:
if currentnode.left is None and currentnode.right is None:
return depth
I'm trying to figure out a recursive solution to this problem. The main thing is to return the level in the binary tree where the node is.
def find_depth(tree, node):
if node == None:
return 0
else:
return max(find_depth(tree.left))
#recursive solution here
Using this class for the values:
class Tree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
Example: Calling find_depth(tree, 7) should return the level where 7 is in the tree. (level 2)
3
/ \
7 1 <------ return that 7 is at level 2
/ \
9 3
maybe this is what you are looking for
def find_depth(tree, node):
if node is None or tree is None:
return 0
if tree == node:
return 1
left = find_depth(tree.left, node)
if left != 0:
return 1 + left
right = find_depth(tree.right, node)
if right != 0:
return 1 + right
return 0
You need to provide information about depth in find_depth call. It might look like this (assuming 0 is a sentinel informing that node is not found):
def find_depth(tree, node, depth=1):
if node == None:
return 0
if tree.value == node:
return depth
left_depth = find_depth(tree.left, node, depth+1)
right_depth = find_depth(tree.right, node, depth+1)
return max(left_depth, right_depth)
Then you call it with two parameters: x = find_depth(tree, 7).
Recursion is a functional heritage and so using it with functional style yields the best results -
base case: if the input tree is empty, we cannot search, return None result
inductive, the input tree is not empty. if tree.data matches the search value, return the current depth, d
inductive, the input tree is not empty and tree.data does not match. return the recursive result of tree.left or the recursive result of find.right
def find (t = None, value = None, d = 1):
if not t:
return None # 1
elif t.value == value:
return d # 2
else:
return find(t.left, value, d + 1) or find(t.right, value, d + 1) # 3
class tree:
def __init__(self, value, left = None, right = None):
self.value = value
self.left = left
self.right = right
t = tree \
( 3
, tree(7, tree(9), tree(3))
, tree(1)
)
print(find(t, 7)) # 2
print(find(t, 99)) # None
You can implement the find method in your tree class too
def find (t = None, value = None, d = 1):
# ...
class tree
def __init__ #...
def find(self, value)
return find(self, value)
print(t.find(7)) # 2
print(t.find(99)) # None
I'm writing code to implement a Binary Search Tree in Python. I ran into problems in writing the insert function, which should add a new node at the correct in order location in the tree. I wrote it in two different ways: insertNode1 works fine (correctly performs an insert on the tree), but insertNode2 does not perform the insertion properly. When I Do InOrderTraversal for the tree using insertNode1 and insertNode2, it turned out that the 'insertNode1' yields the full tree while the 'insertNode2' only yields the root.
Why is it that insertNode1 succeeds while insertNode2 fails, and what are the meaningful differences between the two functions that cause this to be the case?
Here's my code:
def insert(self,val):
if not self.root:
self.root = TreeNode(val)
else:
self.insertNode2(self.root, val)
def insertNode1(self,node, val):
if val < node.val:
if not node.left:
node.left = TreeNode(val)
else:
self.insertNode1(node.left,val)
else:
if not node.right:
node.right = TreeNode(val)
else:
self.insertNode1(node.right, val)
def insertNode2(self, node, val):
if not node:
node = TreeNode(val)
else:
if node.val > val:
self.insertNode2(node.left, val)
else:
self.insertNode2(node.right, val)
insertNode2 doesn't correctly perform an insertion as expected because of the line node = TreeNode(val), which makes a purely local assignment to node. This new object is never set to its parent .left or .right property and is lost when the function returns. The root node will not be modified in any run of this function.
Either use the already-working insertNode1, or add a return node statement to insertNode2 and make an assignment in the parent function call scope to the new child.
Here's a snippet demonstrating how that might be done:
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinarySearchTree:
#staticmethod
def p(root, depth=0):
if root:
print(" " * depth + str(root.val))
BinarySearchTree.p(root.left, depth + 2)
BinarySearchTree.p(root.right, depth + 2)
#staticmethod
def insert(node, val):
if not node:
return TreeNode(val)
elif node.val > val:
node.left = BinarySearchTree.insert(node.left, val)
else:
node.right = BinarySearchTree.insert(node.right, val)
return node
if __name__ == "__main__":
root = TreeNode(5)
for n in [2, 1, 3, 7, 9, 6]:
BinarySearchTree.insert(root, n)
BinarySearchTree.p(root)
Output:
5
2
1
3
7
6
9
Which amounts to:
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