%% Plot Binary Tree
% Plot a binary tree with 7 nodes.
% Specify a row vector where each element contains the index of its parent node. Specify the root node with a value of 0. For example, specify the parent of node 1 as 2, the parent of node 2 as 4, the parent of node 3 as 2, and so on.

p = [2 4 2 0 6 4 6]

% Plot the binary tree using treeplot.

treeplot(p)

%
% Generate the coordinates of the tree nodes using the treelayout function. Add text descriptions to show the node indices in the tree plot. Position the text labels 0.02 units to the right of their corresponding nodes.

[x,y] = treelayout(p);
text(x + 0.02,y,{1,2,3,4,5,6,7})

%
% Another alternative to represent the tree structure is to use a digraph object. You can then visualize the structure with plot.
% Create a digraph object using the syntax digraph(s,t) that specifies directed graph edges (s,t) in pairs. Visualize the tree with plot. Suppress the arrows from parent to child nodes by setting the ShowArrows option to false.

g = digraph(p(p~=0),find(p));
plot(g,"ShowArrows",false)

%
% Copyright 2020 The MathWorks, Inc.