二叉树的深度:二叉树的根结点所在的层数为1,根结点的孩子结点所在的层数为2,以此下去。深度是指所有结点中最深的结点所在的层数。
二叉树的宽度:所有深度中含有的最多的子叶数
- public static int getHeight(BiNode head)
- {
- int deep = 0;
- if(head != null)
- {
- int left = getHeight(head.left);
- int right = getHeight(head.right);
- deep = (left>=right)?(left+1):(right+1);
- }
- return deep;
- }
- public static int getWidth(BiNode head)
- {
- if(head == null)
- {
- return 0;
- }
- int nWidth = 0;
- int nTempLastLevelWidth = 0;
- int nCurLevelWidth = 0;
- Queue<BiNode> myQueue = new LinkedList<BiNode>();
- myQueue.add(head);
- nCurLevelWidth = 1;
- nWidth = 1;
- while(!myQueue.isEmpty())
- {
- int nTempLastLevelWidth = nCurLevelWidth ;
- while(nTempLastLevelWidth != 0)
- {
- BiNode tmp = myQueue.poll(); //检索并移除头结点
- if(tmp.left != null)
- {
- myQueue.add(tmp.left);
- }
- if(tmp.right != null)
- {
- myQueue.add(tmp.right);
- }
- nTempLastLevelWidth--;
- }
- nCurLevelWidth = myQueue.size();
- nWidth = nCurLevelWidth>nWidth?nCurLevelWidth:nWidth;
- }
- return nWidth;
- }