I was wondering if someone can review my code for level order traversal in a BST. I am suppose to have [[3],[9,20],[15,7]] but instead I get [[3],[9],[20],[15],[7]] I know I need an outer while loop but, not sure how to construct it.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import queue
class Solution(object):
def levelOrder(self, root):
L = queue.Queue()
local = []
L.put(root)
while not L.empty():
node = L.get()
local.append([node.val])
if(node.left):
L.put(node.left)
if(node.right):
L.put(node.right)
return local
Related
I am trying to solve the Leetcode problem: 102. Binary Tree Level Order Traversal and hit a snag. My code below does not give the correct output and I have been trying to figure out what is the issue since it is not appending the last level in the tree. I would appreciate it someone can assist in making this code work.
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
while not root:
return []
queue = [root]
result = [[queue[0].val]]
while queue:
nodes = queue
level_nodes = []
temp = []
for node in nodes:
level = queue.pop(0)
if node.left:
level_nodes.append(level.left.val)
temp.append(node.left)
if node.right:
level_nodes.append(level.right.val)
temp.append(node.right)
queue = temp
result.append(level_nodes)
return result
Input: root = [3,9,20,null,null,15,7]
Expected Output: [[3],[9,20],[15,7]]
Output I am getting: [[3],[9,20],[]]
Reference: https://leetcode.com/problems/binary-tree-level-order-traversal/description/
I have been able to solve the problem and leave it for reference anyone who is doing it in this way (Not trying to use deque from collisions library). This solution was accepted by LeetCode.
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
while not root:
return []
queue = [root]
result = []
while queue:
level_nodes = []
temp = []
for node in queue:
level_nodes.append(node.val)
if node.left:
temp.append(node.left)
if node.right:
temp.a bppend(node.right)
queue = temp
result.append(level_nodes)
return result
# 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 pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
self.resultpath = []
def dfs(node,target,temp):
if node is None:
return
temp.append(node.val)
print(temp)
if node.left is None and node.right is None and target == node.val:
self.resultpath.append(temp)
dfs(node.left, target-node.val, temp)
dfs(node.right, target-node.val, temp)
dfs(root, targetSum, [])
return self.resultpath
this is really confusing me. For a "Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22"
picture of the tree: https://imgur.com/a/cAK8kQn
As this code goes through the recursions, at temp = [5,4,11], dfs(node.left ...) will turn this into [5,4,11,7] but temp is still [5,4,11], so dfs(node.right ...) should turn this into [5,4,11,2] but the 7 from dfs(node.left ...) shows up to make it [5,4,11,7,2].
Why is that? How would I fix this code so it doesn't do that?
The issue is quite simple. There is only a single temp. You are passing a reference to this single object in all recursive calls, so any mutations in a recursive call to dfs will be visible from the calling scope.
The key is to simply copy temp every time you make a recursive call.
Below in the solution class, I have an implementation of an inorder traversal (left, root, right).
For some reason I am entering into an infinte loop and I wonder if it is becaue of the way python handels consecutive if if/else statements?
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = righ
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
out = []
stack = []
if root is None:
return out
else:
stack.append(root)
while stack != []:
temp = stack.pop()
if temp.right:
stack.append(temp.right)
if temp.left:
a = temp.left
stack.append(temp)
stack.append(a)
else:
out.append(temp.val)
return out
I'm fairly new to programming and I want to screw around with some Binary Search Trees. I want to make a function that counts the number of nodes in the tree recursively, however, when I run my function it doesn't seem to work and it keeps returning 'none' as if there is nothing in my tree. Could anyone help me find the problem here?
This is my TreeNode class:
class TreeNode(object):
def __init__(self, data = None, left=None, right=None):
self.item = data
self.left = left
self.right = right
def __str__(self):
return str(self.item)
This is my main function, I trimmed most of it down just so we can get to the problem referring to the counting of the nodes.
from TreeNode import TreeNode
class BST(object):
#------------------------------------------------------------
def __init__(self):
"""create empty binary search tree
post: empty tree created"""
self.root = None
def treeSize(self, root, size = 0):
if root is None:
return -1
if root is not None:
size += 1
if root.left is not None:
self.treeSize(root.left, size)
if root.right is not None:
self.treeSize(root.right, size)
This is the code I use to test out my function:
from BinarySearchTree import BST
from TreeNode import TreeNode
tree = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode (7, TreeNode(6),TreeNode(8)))
a = BST()
print(a.postOrder(tree))
print(a.treeSize(tree))
When I called the 'print(a.treeSize(tree))' It just returns 'none' and not '7' like it should.
You can also do it the good old recursive way:
def treeSize(self, root):
if root is None:
return 0
if root is not None:
return 1 + self.treeSize(root.left) + self.treeSize(root.right)
Jonathan's answer is nice as well.
I see. You think size is going to get updated in the called functions. It won't as it's local to each function. You could call global on it, but that's not optimal.
You could set it as a member variable (don't actually do it this way):
def __init__(self):
...
self.size = 0
def treeSize(self,...):
...
self.size += 1
...
return self.size
but the obvious bug is self.size will double every time treeSize is called. You can fix that too, but let's use patterns we know and love. Do it the good old recursive way like VHarisop wrote.
I am reviewing for my final and one of the practice problem asks to implement a function that puts a value into a binary search tree in Python. Here is the Tree implementation I am using.
class Tree(object):
def __init__(self, entry, left=None, right=None):
self.entry = entry
self.left = left
self.right = right
Here is the function I need to fill in.
def insert(item, tree):
"""
>>> t = Tree(5, Tree(1, None, Tree(4)), Tree(7, Tree(6), Tree(8)))
>>> insert(2, t)
>>> t
Tree(5, Tree(1, None, Tree(4, Tree(2), None)), Tree(7, Tree(6), Tree(8)))
"""
Can anyone help me implement this code, as I have no idea where to start? Thanks!
def insert(item, tree):
if (item < tree.entry):
if (tree.left != None):
insert(item, tree.left)
else:
tree.left = Tree(item)
else:
if (tree.right != None):
insert(item, tree.right)
else:
tree.right = Tree(item)
Tree is a Non linear data structure.A tree is created by set of vertices and set of edges.Average searching complexity is logn . Let's consider how to insert values to tree.
First of all , you would create a Vertices.In another way, you would create nodes.then , Those nodes which is created insert hierarchical manner.In creating Node class , You can initialize all the properties of Node class in constructor function.Actually like this,
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
At beginning, Node's data=data, left child of Node is None and right child of Node is None.And then , you can create a binary search tree using those created nodes.
class tree:
def __init__(self):
self.root=None
def insert(self,data):
if(self.root==None):
self.root=Node(data)
else:
self._insert(data,self.root)
def _insert(self, data, curNode):
if(curNode.data>data):
if(curNode.left==None):
curNode.left=Node(data)
else:
self._insert(data,curNode.left)
else:
if(curNode.right==None):
curNode.right=Node(data)
else:
self._insert(data,curNode.right)
At first, root node is initialized under constructor method of tree class.And then insert nodes using insert function.Using any tree traversal method can be printed elements of tree..I think , you could understand.thank you!