所谓二叉树宽度,就是至每一层节点数多的那一层的节点数
我的算法大致思路是:
开辟一个数组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 }