【问题标题】:How can I make recursive function for binary tree in matlab如何在matlab中为二叉树制作递归函数
【发布时间】:2018-10-28 22:36:16
【问题描述】:

V 是一个图像矩阵。D0 和 D1 是级别 1 的二叉树的左右根。 这是一棵二叉树,它有 8 级。这意味着很多代码。我想用递归函数来实现它。作为输出,我需要数组 M 中的所有均值根。请任何想法让它递归?

clear all;clc;
V=imread('tire.tif');
[x y]=size(V);
U=V*0;

  M=zeros(1,511);


  % LEVEL 1
  M(1,1)=mean(V(:));

  % LEVEL 2
  D0=V(V<=mean(V(:))); % right root for V
  M(1,2)=mean(D0(:));
  D1=V(V>mean(V(:)));  %left root for V
  M(1,3)=mean(D1(:));

  % LEVEL 3
  D00=D0(D0<=mean(D0(:)));  %left root for D0
  M(1,4)=mean(D00(:));
  D01=D0(D0>mean(D0(:)));  %left root for D0
  M(1,5)=mean(D01(:));

  D10=D1(D1<=mean(D1(:)));   %right root for D1
  M(1,6)=mean(D10(:));
  D11=D1(D1>mean(D1(:)));    %left root for D1
  M(1,7)=mean(D11(:));

【问题讨论】:

    标签: matlab recursion binary-search-tree


    【解决方案1】:

    我相信这是您正在寻找的解决方案。棘手的部分是跟踪索引(像往常一样)。

    function M = myrecfun(V, M, n_max, n, i)
    %n: current level (of recursions)
    %i: an integer in [1, 2^(n-1)]
    i_start = 2^n;
    meanV = mean(V(:));
    if n == 1
    M(1) = meanV
    end 
    DR = V(V <= meanV);
    DL = V(V > meanV);
    iR = i_start + 2*i - 2;
    iL = i_start + 2*i - 1;
    M(iR) = mean(DR);
    M(iL) = mean(DL);
    if n < n_max
    M = myrecfun(DR, M, n_max, n+1, iR - i_start + 1);
    M = myrecfun(DL, M, n_max, n+1, iL - i_start + 1);
    else % else of if n < n_max
    M;
    end % end of  if n < n_max
    end % of myrecfun
    

    调用代码:

    n_max = 8;
    V = 100*rand(100,100); %Just my example
    M = zeros(1, 2^(n_max+1)-1);
    Mout = myrecfun(V, M, n_max, 1, 1);
    

    测试输出:

    总和(口

    ans =

    256

    总和(Mout > 50)

    ans =

    255

    【讨论】:

    • 非常感谢您对我的问题感兴趣。它给 iL 一个错误???未定义的函数或变量“iL”。 ==> myrecfun 在 15 M(iL) = mean(DL) 处的错误; ==> denemerecrsve 中的错误 4 Mout = myrecfun(V, M, n_max, 1, 1); >> @bbarker
    • 我写 iL = i_start + 2*i -1;代码运行良好,感谢您的帮助
    • 我以为它在那里,但有一个缩进问题:现在已修复。
    • 你在 MATLAB 中有 smqt 源吗?如果可以,可以给我吗?
    猜你喜欢
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2016-07-24
    • 1970-01-01
    • 2014-07-14
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多