accessing binary search tree using struct in a for loop

Viewed 59

I want to create a binary tree in MATLAB. So I tried putting structs in structs to represent the nodes. The basic idea is as follows

node3 = struct('left',0,'value',5,'right',1);
node2 = struct('left',node3,'value',6,'right',1);
tree = struct('left',node2,'value',nan,'right',1);

say if I wan to create a path of my binary tree for the first element(row 1) of my matrix with value of 1100 (top_node->right->right->left->left->1). I wanted to do this in a for loop and add structs to tree as I got on as shown above.

it should look something like that

array = [1 1 0 0; 1 0 0 0; 1 1 1 1; 0 0 0 0] %such that 1100 returns 1 and 1000 returns 2 and so on 

for j=1:4
  for i=1:4   
     if (array(1,i) == 0)) 
       node = struct('left',0,'value',nan,'right',1); %temp node %the nan will be 1 when it reaches the last node
       tree.left = node;
     elseif (array(1,i) == 1))
       node = struct('left',0,'value',nan,'right',1);
       tree.right = node;
    end 
  end
end

This code is perfectly fine if I was trying to implement it for 1 iteration. Adding the second struct (up to 11) would be difficult because I would then have to use tree.right.right = node, and adding the 3rd struct (up to 110) would be tree.right.right.left = node. Unlike other languages such as c, there is no pointers in MATLAB. This makes it impossible for me to implement it inside a for loop as the path gets longer.

Is there a way to solve this or is there a better way to implement a binary tree in MATLAB?

0 Answers
Related