#秒杀二叉树深度
1:递归
public int maxDepth(TreeNode root) {
return root==null?0:Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}
递归的思想还是很简单的,再看看第二种思想
2:非递归
这里用到了配对(Pair)。配对提供了一种方便方式来处理简单的键值关联,当我们想从方法返回两个值时特别有用。
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
//pair存储节点和一个数
Stack<Pair<TreeNode, Integer>> stack = new Stack<>();
//把根节点入栈 value为1
stack.add(new Pair<>(root, 1));
int h = 0;
while (!stack.isEmpty()) {
//取出栈顶元素,并用Pair来存储
Pair<TreeNode, Integer> pair = stack.pop();
//比较pair的value值和h
h = Math.max(pair.getValue(), h);
//遍历当前节点左右孩子节点
if (pair.getKey().right != null) {
stack.push(new Pair<>(pair.getKey().right, pair.getValue() + 1));
}
if (pair.getKey().left != null) {
stack.push(new Pair<>(pair.getKey().left, pair.getValue() + 1));
}
}
return h;
}
3: BFS
public int maxDepth(TreeNode root) {
if(root == null) return 0;
List<TreeNode> queue = new LinkedList<>() {{ add(root); }}, tmp;
int res = 0;
while(!queue.isEmpty()) {
tmp = new LinkedList<>();
for(TreeNode node : queue) {
if(node.left != null) tmp.add(node.left);
if(node.right != null) tmp.add(node.right);
}
queue = tmp;
res++;
}
return res;
}
That’s All !