二叉树的深度-Java实现
二叉树的深度
http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b
一. 思路
先判根节点是否为空,为空则直接返回深度为0。用层次遍历方法,每遍历一层,深度就加1。
二. 代码
import java.util.*; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public int TreeDepth(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); int level = 0; if (root == null) return 0; queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } level++; } return level; } }