二叉树 求宽度

来源:互联网 发布:dev c 如何创建c语言 编辑:程序博客网 时间:2024/05/16 19:10
所谓二叉树宽度,就是至每一层节点数多的那一层的节点数

我的算法大致思路是:

开辟一个数组count[二叉树高度],遍历每一个节点,然后根据当前节点所在层次i,则执行count[i]++;

最后遍历完求出最大的count即为二叉树宽度,代码很简单如下

int  count[100];int MAX=-1;void FindWidth(BitNode T,int k){if(T==NULL)  return;count[k]++;if(MAX<count[k]) MAX=count[k];FindWidth(T->lchild,k+1);FindWidth(T->rchild,k+1);}//MAX即为所求宽度


 使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。

复制代码
 1 // 获取最大宽度 2     public static int getMaxWidth(TreeNode root) { 3         if (root == null) 4             return 0; 5  6         Queue<TreeNode> queue = new ArrayDeque<TreeNode>(); 7         int maxWitdth = 1; // 最大宽度 8         queue.add(root); // 入队 9 10         while (true) {11             int len = queue.size(); // 当前层的节点个数12             if (len == 0)13                 break;14             while (len > 0) {// 如果当前层,还有节点15                 TreeNode t = queue.poll();16                 len--;17                 if (t.left != null)18                     queue.add(t.left); // 下一层节点入队19                 if (t.right != null)20                     queue.add(t.right);// 下一层节点入队21             }22             maxWitdth = Math.max(maxWitdth, queue.size());23         }24         return maxWitdth;25     }
复制代码


0 0
原创粉丝点击