输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度,根节点的深度视为 1 。
数据范围:节点的数量满足 0≤n≤100 ,节点上的值满足 0≤val≤100
进阶:空间复杂度 O(1) ,时间复杂度 O(n)
假如输入的用例为{1,2,3,4,5,#,6,#,#,7},那么如下图:

输入:{1,2,3,4,5,#,6,#,#,7}
返回值:4
输入:{}
返回值:0
- /**
- 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) {
- if (root == null) {
- return 0;
- }
-
- Deque
stack = new ArrayDeque<>(); - stack.offerLast(root);
- int depth = 0;
-
- while (!stack.isEmpty()) {
- depth++;
- int length = stack.size();
-
- while (length-- > 0) {
- TreeNode node = stack.pollFirst();
- if (node.left != null) {
- stack.offerLast(node.left);
- }
-
- if (node.right != null) {
- stack.offerLast(node.right);
- }
- }
- }
-
- return depth;
- }
- }
使用广度优先遍历,用队列存放二叉树的节点,每遍历一层,二叉树的深度加一。