104. Maximum Depth of Binary Tree

题目

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.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

##分析 求二叉树的最大深度
##解答 ###解法1:(我)递归(1ms) ``` public class Solution { public int maxDepth(TreeNode root) { if (root == null)//根节点为null return 0; else if (root.left == null && root.right == null)//根节点的左右孩子都为null return 1; else if (root.left != null && root.right != null)//根节点的左右孩子都不为null return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1; else if(root.left == null)//根节点的左孩子为null,右孩子不为null return maxDepth(root.right) + 1; else//根节点的右孩子为null,左孩子不为null return maxDepth(root.left) + 1; } } ```  
###解法2:(我)解法1的优化(1ms) ``` public class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; else return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1; } } ```  
###解法3:解法2的优化(1ms√) ``` public class Solution { public int maxDepth(TreeNode root) { return (root == null) ? 0 : Math.max(maxDepth(root.left),maxDepth(root.right)) + 1; } } ```
posted @ 2017-02-18 10:54  妙音天女  阅读(167)  评论(0编辑  收藏  举报