二叉树的宽度

二叉树某一层的宽度指的是该层中节点的个数。而二叉树的宽度是指所有层中宽度的最大值。
注:若二叉树为空,则返回0。
输入、输出描述
输入:
给定一个二叉树的根节点
输出:
二叉树的宽度
Example
输入:
二叉树如下:
    1
   / \
   2  3
  /  / \
  4  5  6
   \
    7
输出:
3
代码:
import java.util.*;

public class Main {

    /**
    //该段代码仅用于调试,提交时请注释该段代码
    class TreeNode<T> {

        public T data;

        public TreeNode<T> left;

        public TreeNode<T> right;
    }
 */ 

public int solution(TreeNode<Integer> root) {
	if(root ==null){
		
		return 0;
	}
	Queue<TreeNode<Integer>> q = new LinkedList<>();
	TreeNode<Integer>p=root;
	q.add(p);
	int max = 0x80000000;
	while (q.isEmpty() == false)
	{	
		List<Integer> list = new ArrayList<>();
		
		int sz = q.size();
		if(max < sz){
			max = sz;
		}
		while(sz != 0){
             p = q.poll();
             if(p.left != null){
                 q.add(p.left);
             }
             if(p.right != null){
                 q.add(p.right);
             }
			 sz--;
       }
	   
	}
	return max;
}
}
一个创业中的苦逼程序员
评论专区

隐藏