The reason this doesn't work is that res only has the value of the first node you give it appended to it; each time you recursively recall the function, it just makes a new res. It is a simple fix though, as follows:

class Solution(object):
    def inorderTraversal(self, root):
        res = []
        if root:
            res = self.inorderTraversal(root.left) 
            res.append(root.val)
            res = res + self.inorderTraversal(root.right)
        return res

In this, it returns the left branch, the value, and then the right. This can be done much more briefly as follows:

class Solution(object):
    def inorderTraversal(self, root):
        return (self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)) if root else []
Answer from Benedict Randall Shaw on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ tree-traversal-techniques-in-python
Tree Traversal Techniques in Python - GeeksforGeeks
July 23, 2025 - In the driver code section (if __name__ == "__main__":), a sample binary tree with seven nodes is constructed and the printInorder function is called to display the inorder traversal of the tree. The output would be the values of the nodes in the order they are visited using the inorder traversal method. ... # Python3 code to implement the approach # Class describing a node of tree class Node: def __init__(self, v): self.left = None self.right = None self.data = v # Inorder Traversal def printInorder(root): if root: # Traverse left subtree printInorder(root.left) # Visit node print(root.data,e
๐ŸŒ
Medium
medium.com โ€บ @arjunprakash027 โ€บ binary-searchtree-and-its-algorithms-in-python-1a116c852c1b
Binary Search Tree and Traversal algorithms in python
November 3, 2023 - As the recursion proceeds, the results from all subtrees, both left and right, are appended to the res list, gradually building up the preorder traversal order of the entire tree. This approach effectively visits the center node first, followed by the left and right subtrees, resulting in a preorder traversal of the binary tree.
Discussions

list - Inorder Binary Tree Traversal (using Python) - Stack Overflow
I am trying to perform an inorder traversal of a tree. The code itself feels right, except it is not working properly. I have a feeling it has to either do with the if condition, how append works in More on stackoverflow.com
๐ŸŒ stackoverflow.com
Traversing a binary tree in Python - Stack Overflow
I am almost finished with a project that has us creating a dictionary class that utilizes a binary tree structure. I am however stuck on how to implement a method that prints out all the elements i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Binary Tree Traversal Using Recursion Explanation (python) - Stack Overflow
I am currently studying Binary trees. I came across this very efficient code for traversing through the tree ( in the example this is an in order traversal ). It uses recursion, which as a concept I More on stackoverflow.com
๐ŸŒ stackoverflow.com
4 Ways to Traverse a Binary Tree
good explain! More on reddit.com
๐ŸŒ r/computerscience
5
17
September 7, 2020
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ getting-deep-into-complex-algorithms-for-interviews-with-python โ€บ lessons โ€บ binary-tree-traversals-in-python
Binary Tree Traversals in Python
We have three primary ways to traverse a binary tree: Inorder (Left, Root, Right), Preorder (Root, Left, Right), and Postorder (Left, Right, Root). One way is to use recursive Inorder traversal. If a tree is not empty, we will first recursively traverse the left subtree, then visit the root, ...
๐ŸŒ
DEV Community
dev.to โ€บ kodebae โ€บ understanding-binary-tree-traversal-in-python-11hm
How To Traverse A Binary Tree in Python - DEV Community
October 10, 2023 - Here is what an inorder traversal could look like in Python: class TreeNode: def _init_(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def helper(root, res): if root is None: return helper(root.left, res) <----- The left res,append(root.val) <----- The Node!!!
๐ŸŒ
Educative
educative.io โ€บ blog โ€บ how-to-traverse-a-binary-tree-in-python
How To Traverse A Binary Tree in Python
For space-constrained in-order on binary trees, consider Morris traversal, which temporarily threads the tree to achieve O(1) extra space (but it mutates pointers during traversal and is less beginner-friendly).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ inorder-traversal-of-binary-tree
Inorder Traversal of Binary Tree - GeeksforGeeks
Python ยท #Node Structure class Node: def __init__(self, x): self.data = x self.left = None self.right = None def inOrder(node, res): if node is None: return # Traverse the left subtree first inOrder(node.left, res) # Visit the current node res.append(node.data) # Traverse the right subtree last inOrder(node.right, res) if __name__ == "__main__": # Create binary tree # 1 # / \ # 2 3 # / \ \ # 4 5 6 root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) res = [] inOrder(root, res) for node in res: print(node, end=" "
Published: December 8, 2025
Find elsewhere
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_dsa_binarytrees.asp
Python Binary Trees
In-order Traversal does a recursive In-order Traversal of the left subtree, visits the root node, and finally, does a recursive In-order Traversal of the right subtree. This traversal is mainly used for Binary Search Trees where it returns values ...
๐ŸŒ
Medium
medium.com โ€บ plain-simple-software โ€บ mastering-binary-tree-traversals-a-comprehensive-guide-d7203b1f7fcd
Mastering Binary Tree Traversals: A Comprehensive Guide | by Adam DeJans Jr. | Plain Simple Software | Medium
February 15, 2024 - Traversing a binary tree is a core operation that involves visiting each node exactly once in a specific order. This article delves into the three primary traversal strategies: pre-order, in-order, and post-order.
๐ŸŒ
Medium
medium.com โ€บ quick-code โ€บ binary-tree-traversal-python-implementation-f69c405bb286
Binary Tree Traversal โ€” Python Implementation
August 28, 2019 - Time complexity in traversing is O(n). Below is a given script to find the total no. of nodes in a binary tree:
๐ŸŒ
Learnsteps
learnsteps.com โ€บ binary-tree-traversal-using-python
Binary tree and its traversal using python. Inorder, preorder and postorder
November 3, 2019 - So this is how you write the binary tree in Python. We made a class Node which represent the node of Binary tree. We initialize the node with data and left and right child as None. When we add new child we simple use root.left or root.left.left to add a new child. Now lets have a look at the traversal functions.
๐ŸŒ
Upskly AI
upsklyai.com โ€บ home โ€บ dsa โ€บ binary tree in python: traversals explained
Binary Tree in Python: Traversals Explained - Upskly AI
2 weeks ago - Python has no built-in one, so you create a TreeNode class with value, left and right. Depth-first traversals (preorder, inorder and postorder) and breadth-first traversal (level-order).
Top answer
1 of 4
3

There is another solution for recursive in-order tree traversal using Python 3's yield from:

def traverse(tree):
    if tree.left is not None:
        yield from traverse(tree.left)

    yield tree.value

    if tree.right is not None:
        yield from traverse(tree.right)

print(list(traverse(tree_root)))

I think it's far more readable and conceptually simple. I hope it will be helpful to somebody.

2 of 4
2

All you need to do is create a helper method visitAllSubnodes(node) which does something to the current node, then recursively calls itself on the left and right subnodes. What visitAllSubnodes(node) does can be anything, in your case it could be something like print(node._element), but you can make your function wonderfully modular, e.g.

def visitAllSubnodes(node, whatToDoAtEachNode):
    whatToDoAtEachNode(node)
    visitAllSubnodes(node._left, whatToDoAtEachNode)
    visitAllSubnodes(node._right, whatToDoAtEachNode)

def printAllElements(node):
    visitAllSubnodes(node, lambda x:print(x))

To actually return something, you need to use the concept of higher order functions and closures. For example, you could make a function which defines a private personal accumulator (a list you add to), and another function to which that private personal accumulator belongs to, then return the function.

So for example, each time traversed the tree, you could invoke this higher order function, let's call it makeFunctionWhichKeepsTrackOfWhatHasBeenPassedIntoIt(), which returns a function that keeps track of what has been passed into it, as well as the accumulator. I'd give more info but that would be the point of the problem set. =)

๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ tree-traversal-python-with-recursion
Tree Traversal in Python (Inorder, Preorder & Postorder)
May 16, 2023 - Using tree data structure, it becomes ... and path accordingly. Tree traversing in Python refers to the process of visiting each node in a data structure like a tree....
Top answer
1 of 2
1

One useful tool for understanding the path that an algorithm takes is to add logging to it.

    def inorder_print(self, start, traversal, indent=""):
        """Left -> root -> right"""
        if start:
            print(f"{indent} {start.data} <- '{traversal}'")
            traversal = self.inorder_print(start.left, traversal, indent+" ")
            traversal += (str(start.data) + "-")
            print(f"{indent} {start.data} -- '{traversal}'")
            traversal = self.inorder_print(start.right, traversal, indent+" ")
            print(f"{indent} {start.data} -> '{traversal}'")

        return traversal

allows us to visualize the tree and the order in which each node is added to the traversal:

 1 <- ''
  2 <- ''
   4 <- ''
   4 -- '4-'
   4 -> '4-'
  2 -- '4-2-'
   5 <- '4-2-'
   5 -- '4-2-5-'
   5 -> '4-2-5-'
  2 -> '4-2-5-'
 1 -- '4-2-5-1-'
  3 <- '4-2-5-1-'
   6 <- '4-2-5-1-'
   6 -- '4-2-5-1-6-'
   6 -> '4-2-5-1-6-'
  3 -- '4-2-5-1-6-3-'
   7 <- '4-2-5-1-6-3-'
   7 -- '4-2-5-1-6-3-7-'
    8 <- '4-2-5-1-6-3-7-'
    8 -- '4-2-5-1-6-3-7-8-'
    8 -> '4-2-5-1-6-3-7-8-'
   7 -> '4-2-5-1-6-3-7-8-'
  3 -> '4-2-5-1-6-3-7-8-'
 1 -> '4-2-5-1-6-3-7-8-'

The indentation shows the depth of the stack. Each individual recursive call has three parts -- the left child, self.data, and the right child.

The code "knows" that 2 goes after 4 because 4 happens at the start of 2's call, and the string '2-' is appended immediately afterward:

  2 <- ''          # start of 2's call.  2 starts by calling 4
   4 <- ''             # start of 4's call
   4 -- '4-'           # 4 appends self.data
   4 -> '4-'           # end of 4's call, returning to 2
  2 -- '4-2-'      # 2 appends self.data to what it got from 4, and calls 5
   5 <- '4-2-'         # start of 5's call
   5 -- '4-2-5-'       # 5 appends self.data
   5 -> '4-2-5-'       # end of 5's call, returning to 2
  2 -> '4-2-5-'    # end of 2's call
2 of 2
0

Ok, sat with it a little longer and figured it out. Thought id post my thoughts so that this question can be marked as answered.

  1. inorder func is called with root and empty string.
  2. start has value of tree.root, while start has value it keeps recursing at traversal = self.inorder_print(start.left, traversal)
  3. it is to be noted, that each time a recursion happens you go further into the tree. start.data = 1. recursion, start.data = 2 recursion, start.data = 4. due to the fact that 4 does not have a left child. the function can finally return. start.data now = 4 and the next line traveral += str(start.data) + "-") can run, adding to the string. However remember that the function is still 2 recurrsions deep. our start.data is back to 2. as that function has finished executing, 2 gets added to traversal via line traveral += str(start.data) + "-")/ #recursion happens with start.right. start.data now =5 start.right has no value, so the function can return 5. this process continues for the whole tree, until all of the functions that have been executed have been completed. the trick to undertanding (at least for me) is that the when you return to a higher level in recursion, the function starts off where it left and doenst start the function from the beginning.
๐ŸŒ
Medium
burpeesdaily.medium.com โ€บ build-the-forest-in-python-series-binary-tree-traversal-e4f88bfb9ddf
Build the Forest in Python Series: Binary Tree Traversal | by Shun Huang | Medium
February 20, 2024 - In-order, pre-order, and post-order traversals are types of depth-first traversal, whereas Level-order traversal is a type of breadth-first traversal. This article will go through these traversal functionsโ€™ implementation in both recursive and iterative ways. The same as Build the Binary Search Tree, the implementation assumes Python 3.9 or newer.
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ examples โ€บ inorder-tree-traversal
Inorder Tree Traversal in Python [Implementation] - AskPython
February 22, 2021 - In the inorder traversal, first, ... recursively till all the nodes are traversed.We use inorder traversal to print elements of a binary search tree in increasing order....
๐ŸŒ
W3Schools
w3schools.com โ€บ dsa โ€บ dsa_algo_binarytrees_inorder.php
DSA In-order Traversal
In-order Traversal does a recursive In-order Traversal of the left subtree, visits the root node, and finally, does a recursive In-order Traversal of the right subtree. This traversal is mainly used for Binary Search Trees where it returns values ...
๐ŸŒ
Reddit
reddit.com โ€บ r/computerscience โ€บ 4 ways to traverse a binary tree
r/computerscience on Reddit: 4 Ways to Traverse a Binary Tree
September 7, 2020 -

Brush up with Tree Data Structure

Here's a Binary Search Tree (BST). Every circle is called a node and each node can be connected to 2 other nodes -- one on the left and right. That's why they're called Binary Trees, they have 2 "child" nodes and it looks like a tree!

A Binary Tree

The left child node is always smaller or equal in value than the parent, and the right is always greater or equal. Some implementations allow only the left or right node to be equal to the parent. Personally, I like putting equal nodes, to the left side ๐Ÿ˜

BTW, here's a Binary Search Tree using python3!

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

The default values for the left and right tree are null/None and default val is 0.

Traversals

For each traversal I'm going to give a brief description of how it moves through the binary tree, starting from the root (the top). Then show the code for traversal using python and lastly a GIF visualizing how the program moves through the tree! Also all of the gifs will end early without going through the entire tree because the gif sizes were getting too big and I had to cut it short ๐Ÿคทโ€โ™‚๏ธ.

The first 3 are very similar and only differ by one line of code but give very different results! I call them the traversal triplets.

In Order

This method moves through the tree "in order". Meaning that it will print every nodeโ€™s value in order from smallest to greatest.

Using recursion, the function will call itself on the left sub-tree, then print the current value, and then call itself on the right sub-tree. The result is that it prints the tree's values.... in order.

def in_order(node):
    if node == None:
        return
    in_order(node.left)
    print(node.val)
    in_order(node.right)
In Order Traversal Animation

Depth-First Search (also known as pre-order)

Depth-First Search is the classic traversal method for trees and also graphs. This method is also known as the pre-order traversal because it first operates on the current node, then the left and right child nodes.

Depth first search is very popular for general traversal as well as making copies of the tree.

def dfs(node):
    if node == None:
        return
    print(node.val)
    dfs(node.left)
    dfs(node.right)
DFS Traversal Animation

Post Order

The last of the traversal triplets. It first operates on the left and right child nodes then the current node.

Post Order is very useful for deleting a tree, as it goes from the bottom up.

def post_order(node):
    if node == None:
        return
    post_order(node.left)
    post_order(node.right)
    print(node.val)
Post Order Traversal Animation

Breadth-First Search (also Level Order)

This one is a little more tricky and can only be done using a queue. It might be possible with recursion but it's easier to understand iteratively. It uses a queue when traversing so it goes through the tree as nodes are added to it. As a result, it goes through the tree, level by level. This makes breadth-first search a popular search algorithm in graphs as well.

Although I couldn't make an animation for this one, I created a numbered diagram to show what order the nodes would be printed!

# deque is a python queue library
from collections import deque

def bfs(root):
    q = deque([root])
    while len(q) > 0:
        node = q.popleft()
        print(node.val)
        if node.left:
            q.append(node.left)
        if node.right:
            q.append(node.right)
Numbered Level Order Traversal

Conclusion

By understanding these 4 traversal methods, you can demystify most interview problems involving binary trees. A lot of them can be broken down into easily solvable chunks if you know the right traversal method to use! If you're curious about the exact methodology, I've got a guide coming out soon! I hope it'll be the only resource needed for solving binary tree problems.

Also, all animations were courtesy of http://btv.melezinek.cz/binary-search-tree.html. Make sure to check them out if you want to play around with the animations!

By The Way I'm Making a Guide

I'm making a guide on how to solve almost any Binary Tree problem on LeetCode (and therefore in an interview)! Join me on my journey by following me on Twitter!

๐ŸŒ
MakeUseOf
makeuseof.com โ€บ home โ€บ programming โ€บ how to traverse a binary search tree
How to Traverse a Binary Search Tree
August 1, 2023 - The space complexity of all the traversal techniques is O(h), where h is the height of the binary tree. The size of the binary tree is equal to the number of nodes in that tree. The height of the binary tree is the number of edges between the tree's root node and its farthest leaf node. Below is a Python program to perform all three binary search tree traversals: