题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.LinkedList; import java.util.Queue; public class Solution { public int TreeDepth(TreeNode root) { Queue<TreeNode> tree = new LinkedList<>(); if (root != null) { tree.add(root); } int length = 0; while (!tree.isEmpty()) { int size = tree.size(); while (size > 0) { TreeNode node = tree.peek(); if (node.left != null) { tree.add(node.left); } if (node.right != null) { tree.add(node.right); } tree.remove(node); size--; } length++; } return length; } }
解题思想:
* 方式一:递归左右子树
* 方式二:使用队列层次计算深度
#算法##算法笔记#