二叉树递归函数 [英] Binary Tree Recursive Function

查看:113
本文介绍了二叉树递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打印出一个像这样的二叉树:

I need to print out a binary tree that looks like this:

--------x-------
----x-------x---
--x---x---x---x-
-x-x-x-x-x-x-x-x 
xxxxxxxxxxxxxxxx

使用递归打印该行的左侧和该行的右侧(第一行除外).因此,该函数将调用带有左起点和右终点参数的显示函数.然后,它会自我调用两次,在左侧调用一次,在右侧调用一次.

Using recursion to print the left side of the line and the right side of the line with the exception of the first line. So the function would call a display function with parameters of the left starting point and the right ending point. Then it calls itself twice, on for the left side and one for the right.

    #include <stdio.h>

#define LENGTH 16

void makeBranches(int, int);
void display(int, int);

int main(){

  makeBranches(0, LENGTH-1);
}

void makeBranches(int left, int right){

  if(left >= right){
    return;
  } else{
    display(left, right);
      makeBranches(left, (right+left)/2);
      makeBranches((right+left)/2+1, right);  
  }
}

void display(int left, int right){
  int mid = (left+right)/2;
  int i;

  for(i = left; i <= right; i++){
    if(i == mid)
      printf("X");
    else
      printf("-");
  }

  if(right == LENGTH-1)
    printf("\n");

}

这是我的代码当前的样子,尽管它已经更改了很多次.

This is currently what my code looks like, although it has changed many times.

我不知道如何执行makeBranches的第一个调用,然后再执行第二个调用.现在,它仅执行左侧调用,如下所示:

I cannot figure out how to get the first call of makeBranches execute and then the second call. Right now it only does the left side calls and looks like this:

-------X--------
---X-----X--X-

推荐答案

您将需要执行广度优先遍历.

这篇关于二叉树递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆