I am trying to make a binary search tree in MATLAB just like how you would do it in java or C++, and fill the nodes with characters. I understand that the nodes can be made with a struct, but I can't understand how to connect them so that it becomes a binary tree.
My struct has the following fields: left
(for the node with the lower value), value
, and right
(for the node with a higher value).
You should use an array of your struct, and use the array index instead of a pointer. So with your struct:
node = struct('left',[],'right',[],'value',0);
you can add a node like so:
node(2).value = 1;
node(1).left = 2; % the index of the new node
creating a tree where node(2)
is the left child of node(1)
.
isempty(node(i).left)
means that node i
has no left child.