帮我找一段function Sltreen的Matlab代码
function [T, root] = Sltree(n) % Sltree - Construct a sorted binary tree of size n. % % Inputs: % n - The number of elements in the tree. % % Outputs: % T - The sorted binary tree as an n-by-3 matrix, where each row represents % a node in the tree. The first column is the node value, the second % column is the index of the left child, and the third column is the % index of the right child. Since the tree is sorted, the nodes are % listed in ascending order. % root - The index of the root node. % % Example: % [T, root] = Sltree(7) % % Author: Tianyu Liu (liuty10@gmail.com) % Date: 2018/7/31
T = zeros(n, 3); T(1, 1) = randi(100); % Set the value of the root node randomly.
for i = 2:n T(i, 1) = randi(100); % Set the value of the new node randomly. j = 1; % Start from the root node. while true % If the new node value is less than the current node value, go left. if T(i, 1) <= T(j, 1) if T(j, 2) == 0 T(j, 2) = i; % Set the left child of the current node. break; else j = T(j, 2); % Continue searching in the left subtree. end % If the new node value is greater than the current node value, go right. else if T(j, 3) == 0 T(j, 3) = i; % Set the right child of the current node. break; else j = T(j, 3); % Continue searching in the right subtree. end end end end
root = find(T(:, 2) == 1); % Find the index of the root node
原文地址: http://www.cveoy.top/t/topic/hoD8 著作权归作者所有。请勿转载和采集!