[leetcode]104. Maximum Depth of Binary Tree@Java解题报告

来源:互联网 发布:淘宝售后处理规则 编辑:程序博客网 时间:2024/05/16 07:51

https://leetcode.com/problems/maximum-depth-of-binary-tree/description/


Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


package go.jacob.day806;import java.util.LinkedList;import java.util.Queue;public class Demo3 {/* * 解法一: * 递归解法,非常简洁 */public int maxDepth(TreeNode root) {if(root==null)return 0;return 1+Math.max(maxDepth(root.left), maxDepth(root.right));}/* * 解法二: 使用queue进行层序遍历 */public int maxDepth_1(TreeNode root) {if (root == null)return 0;Queue<TreeNode> queue = new LinkedList<TreeNode>();int res = 0;queue.add(root);while (!queue.isEmpty()) {int size = queue.size();for (int i = 0; i < size; i++) {TreeNode node = queue.poll();if (node.left != null)queue.add(node.left);if (node.right != null)queue.add(node.right);}res++;}return res;}private class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}}




阅读全文
0 0
原创粉丝点击