Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9271419
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T15:36:54+00:00 2026-06-18T15:36:54+00:00

I am trying to traverse a Binary Tree which is created in the following

  • 0

I am trying to traverse a Binary Tree which is created in the following code. to be precise, the Binary Tree is a class and should include an iterator calling another function namely inorder(). this method should be a recursive generator and yield the value of nodes in every iteration.I tried to create a dictionary to follow the nodes but when I try to call the inorder() method, it doesn’t work. Is there any missing point that I don’t know? I used while and it creates the dictionary of left side of tree (it is a clumsy way).
please help me accomplish this code.

d=[]

# A binary tree class.
class Tree(object):
    def __init__(self, label, left=None, right=None):
        self.label = label
        self.left = left
        self.right = right
        self.d=dict()
    def __repr__(self, level=0, indent="    "):
        s = level * indent + self.label
        if self.left:
            s = s + "\n" + self.left.__repr__(level + 1, indent)
        if self.right:
            s = s + "\n" + self.right.__repr__(level + 1, indent)
        return s

def traverse(self):
    if self.left:
        lastLabel=self.label
        self.left.traverse()
    if self.right:
        lastLabel=self.label
        d.append(lastLabel)
        self.right.traverse()
    else:
        d.append(self.label)
    return d

def __iter__(self):
    return inorder(self)

# Create a Tree from a list.
def tree(sequence):
    n = len(sequence)
    if n == 0:
        return []
    i = n / 2
    return Tree(sequence[i], tree(sequence[:i]), tree(sequence[i+1:]))

# A recursive generator that generates Tree labels in in-order.
def inorder(t):
    for i in range(len(d)):
        yield d[i]    

def test(sequence):
# Create a tree.
    t = tree(sequence)
# Print the nodes of the tree in in-order.
    result = []
    for x in t:
        result.append(x)
    print x
    print

    result_str = ''.join(result)

# Check result
    assert result_str == sequence
    del d[:]
def main():
    # Third test
    test("0123456789")

    print 'Success! All tests passed!'

if __name__ == '__main__':
    main()

I changed my code again
I accomplished the code but I’m sure it is not the best way to traverse a Binary tree.
I defined a method -traverse()- in my class and returned a list of nodes in order now (which at first wasn’t ordered, so I used sort() method.) then I made a loop over this list in my generator, inorder() function, to yield the element of it.
All your comments are very welcome to optimize the code.
please recommend a proper solution based on the specific Tree class in this code.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T15:36:55+00:00Added an answer on June 18, 2026 at 3:36 pm

    Perhaps I’m missing something, but I’m not sure why the dictionary is relevant in inorder(). Think about what an in-order traversal looks like in general:

    def inorder(t):
        # Process left sub tree
        # Process t
        # Process right sub tree
    

    and so in terms of generators, this would look like:

    def inorder(t):
        if t.left:
            for elem in inorder(t.left):
                yield elem
        yield t
        if t.right:
            for elem in inorder(t.right):
                yield elem
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to traverse Binary search tree with the follwoing code and my
I'm trying to traverse a binary tree in C. My tree contains an AST
I'm trying to traverse a tree via TBB tasks and continuations. The code is
I'm trying to traverse a tree using ANTLR tree commands and recursion. The code
I am trying to traverse a binary tree using twalk() with <search.h> #define _GNU_SOURCE
I am trying to implement a binary search tree. Here is the code I
I'm trying to traverse an AJAX response, which contains a remote web page (an
I'm trying to traverse a 3D KD-Tree in my raytracer. The Tree is correct,
I m new to coding and i m trying to create a binary tree
I am trying to traverse a rss feed in which a tag is present

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.