二叉树的深度

给定一个二叉树,求二叉树的深度,即从跟节点到叶节点的最长路径。
若只有一个顶点,则深度为1,若二叉树为空则返回0。
输入、输出描述
输入:
给定一个二叉树的根节点
输出:
二叉树的深度
Example
输入:
二叉树如下:
    1
   / \
   2  3
  /
  4
   \
    5
输出:
4
代码:
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 len = 0;
	while (q.isEmpty() == false)
	{	
		len++;
		
		int sz = q.size();
		while (sz!=0)
		{
			p=q.poll();
			//printf("%c ",p->val);
			if (p.left != null)
			{
				q.add(p.left);
			}
			if (p.right != null)
			{
				q.add(p.right);
			}
        sz--;
		}
	}
	return len;
  }
}
一个创业中的苦逼程序员
评论专区

隐藏