function t = removeBranches(tree,branches,type)
%PRUNENODES Prune selected branch nodes from tree.

%   Copyright 2017-2019 The MathWorks, Inc

N = length(tree.nodes);

% Find children of these branches and remove them
parents = branches;
tokeep = true(N,1);
kids = [];
while(true)
   newkids = [tree.left(parents); tree.right(parents)];
   newkids = newkids(newkids>0 & ~ismember(newkids,kids));
   if isempty(newkids)
       break
   end
   kids = [kids; newkids];
   tokeep(newkids) = 0;
   parents = newkids;
end

% Convert branches to leaves by removing split rule and children
tree.var(branches) = 0;
tree.cut(branches) = NaN;
tree.children(branches,:) = 0;
if ~isempty(tree.leftclasses)
    tree.leftclasses(branches) = {[]};
end
if ~isempty(tree.rightclasses)
    tree.rightclasses(branches) = {[]};
end

% Get new node numbers from old node numbers
ntokeep = sum(tokeep);
nodenums = zeros(N,1);
nodenums(tokeep) = (1:ntokeep)';

% Reduce tree, update node numbers, update child/parent numbers
tree.parent    = tree.parent(tokeep);
tree.var       = tree.var(tokeep);
tree.cut       = tree.cut(tokeep);
tree.left      = tree.left(tokeep);
tree.right     = tree.right(tokeep);
tree.depth     = tree.depth(tokeep);
tree.size      = tree.size(tokeep);
tree.obscount  = tree.obscount(tokeep);
tree.nodeerror = tree.nodeerror(tokeep);
tree.leftclasses  = tree.leftclasses(tokeep);
tree.rightclasses = tree.rightclasses(tokeep);

if type=='c'
    tree.membership   = tree.membership(tokeep,:);
    tree.wmembership  = tree.wmembership(tokeep,:);
    tree.nodeprob     = tree.nodeprob(tokeep,:);
    tree.impurity     = tree.impurity(tokeep,:);
end

tree.crit      = tree.crit(tokeep);
tree.risk      = tree.risk(tokeep);
tree.nodes     = (1:ntokeep)';

if type=='r'
    tree.nodeprob  = tree.nodeprob(tokeep);
    tree.nodemean  = tree.nodemean(tokeep);
end

mask = tree.parent>0;
tree.parent(mask) = nodenums(tree.parent(mask));
mask = tree.left>0;
tree.left(mask) = nodenums(tree.left(mask));
mask = tree.right>0;
tree.right(mask) = nodenums(tree.right(mask));
t = tree;
end