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 treecurnode
— the variable is for iteration inside of the binary tree
root = curnode = TreeNode(val=1)
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 curnode
is iterated to a new tree node
curnode = curnode.leftcurnode.left = TreeNode(3)