码迷,mamicode.com
首页 > 其他好文 > 详细

计算二叉树的宽度的两种方式

时间:2019-01-27 11:30:27      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:.net   教程   content   pretty   段子   二叉树   net   结构   maxwidth   

二叉树作为一种很特殊的数据结构,功能上有很大的作用!今天就来看看怎么计算一个二叉树的最大的宽度吧。


采用递归方式


下面是代码内容:

int GetMaxWidth(BinaryTree pointer){
    int width[10];//加入这棵树的最大高度不超过10
    int maxWidth=0;
    int floor=1;
    if(pointer){
        if(floor==1){//如果访问的是根节点的话,第一层节点++;
            width[floor]++;
            floor++;
            if(pointer->leftChild)
                width[floor]++;
            if(pointer->rightChild)
                width[floor]++;
        }else{
            floor++;
            if(pointer->leftChild)
                width[floor]++;
            if(pointer->rightChild)
                width[floor]++;
        }
        if(maxWidth<width[floor])
            maxWidth=width[floor];
        GetMaxWidth(pointer->leftChild);
        floor--;//记得退回一层,否则会出错。因为已经Get过了,所以要及时的返回。
        GetMaxWidth(pointer->rightChild);
    }
    return maxWidth;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

采用非递归方式


采用非递归方式计算二叉树的宽度需要借助于队列。代码如下:

int GetMaxWidth(BinaryTree pointer){
    if(pointer==null){
        return 0;
    }
    Queue<BinaryTreeNode> queue=new ArrayDeque<BinaryTreeNode>();
    int maxWidth=1;//最大宽度
    queue.add(pointer);
    while(true){
        int size=queue.size();//计算当前层的节点的个数
        if(size==0){
            break;
        }
        while(size>0){//如果当前层还有节点就进行下去
            BinaryTreeNode node=queue.poll();
            size--;
            if(node->leftChild)
                queue.add(node->leftChild);//当前节点的左子树入队
            if(node->rightChild)
                queue.add(node->rightChild);//当前节点的右子树入队
            maxWidth=Math.max(size,queue.size());
        }
    }
    return maxWidth;//返回计算所得的最大的二叉树的宽度。
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

总结:
不管采用哪种方式,实际上还是利用了对二叉树的遍历的特点来进行的。

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

计算二叉树的宽度的两种方式

标签:.net   教程   content   pretty   段子   二叉树   net   结构   maxwidth   

原文地址:https://www.cnblogs.com/djuwcnhwbx/p/10325772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!