how to use a generator in Python to accomplish Preorder Traversal?

46 Views Asked by At

I want to use a generator in Python to accomplish Preorder Traversal,but I meet some problem and I can't solve it. (In fact, it is leetcode 100 and I want to use my way to solve it.)

the treenode is like that:

# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

and the testcase is like that: enter image description here

and I try to write down the code below

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        def preorder(n):
            yield n.val
            
            if n.left:
                preorder(n.left)
            else:
                yield 'None'

            if n.right:
                preorder(n.right)
            else:
                yield 'None'

        i = iter(preorder(p))
        print(next(i))
        print(next(i))
        print(next(i))
        print(next(i))
        print(next(i))

I except it can print 1,2,4,5,3,but the result is enter image description here

I want to know why it can't accomplish Preorder Traversal correctly?

0

There are 0 best solutions below