104. Maximum Depth of Binary Tree

来源:互联网 发布:诺基亚s40软件下载 编辑:程序博客网 时间:2024/06/01 21:26

104. Maximum Depth of Binary Tree

DescriptionHintsSubmissionsSolutions
Discuss Pick One

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.

题意:求一个二叉树的深度

算法思路:

1.这里先使用递归的方法,递归终止条件:传入的root为空
依次求左右深度,递归root的左右子树
最后return 左右深度最大的那个+1

代码:

package easy;public class MaximumDepthofBinaryTree {public int maxDepth(TreeNode root) {if(null == root){return 0;}int leftDepth = maxDepth(root.left);int rightDepth = maxDepth(root.right);return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;}public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}}





原创粉丝点击