I am learning DSA quite long.. During my learning, I encountered a concept 'Left View Method in Binary Tree'. I am completely scripted my code but there is a error when i tried to give a modified binary tree.
My binary tree view
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Actual left view is 1, 2, 4 but instead of I'm getting 1, 2, 4, 8, the 8 is right view also included. If your know to solve the problem, spot and comment the mistake. It will help in my learning Journey. Thanks in advance 🙂. ( code is below )
# left view method
class Node:
def __init__(self, val):
self.left = None
self.right = None
self.data = val
class Leftview:
def view(self, root):
out = []
maxlevel = [-1]
self._helperrecur(root, 0, maxlevel, out)
for i in range(len(out)):
print(out[i], end=' ')
def _helperrecur(self, root, level, maxlevel, out):
#base condition
if root is None:
return
#main condition
if level > maxlevel[0]:
out.append(root.data)
maxlevel[0] = level
#recursive through tree
self._helperrecur(root.left, level+1, maxlevel, out)
self._helperrecur(root.right, level+1, maxlevel, out)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
lf = Leftview()
lf.view(root)
I am tried another way to change the recursion, left -> right previously but i changed to right -> left to check the right view. Right view is absolutely working fine.
Excepted outcome: 1, 3, 7, 8
My output: 1, 3, 7, 8
code is here,
self._helperrecur(root.right, level+1, maxlevel, out)
self._helperrecur(root.left, level+1, maxlevel, out)
I am expecting, How does right view is comes in left view ? If you knew comment me out,