Visualization of a Binary Tree Creation

Jerry An
2 min readJan 2, 2021

Let’s understand binary tree creation details by a little example.

Class Definition

The Definition ofTreeNode is the following.

class TreeNode:

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

Two Variables

  • root — the variable is useful to access the binary tree
  • curnode — the variable is for iteration inside of the binary tree
root = curnode = TreeNode(val=1)
two tree node object

Create Children

Creating two child tree node, their parent node curnode is used

curnode.left = TreeNode(1)
curnode.right = TreeNode(2)

Iteration within Tree

The variable curnodeis iterated to a new tree node

curnode = curnode.leftcurnode.left = TreeNode(3)

--

--