LeetCode 104. Maximum Depth of Binary Tree

原题链接在这里:https://leetcode.com/problems/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.

题解:

左右最大深度+1记为当前node maximum depth.

终止条件是root == null, 返回0.

Time Complexity: O(n), n is the number of nodes in the tree. Space: O(logn).

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int maxDepth(TreeNode root) {
12         if(root == null){
13             return 0;
14         }
15         return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
16     }
17 }

AC JavaScript:

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {number}
11  */
12 var maxDepth = function(root) {
13     if(!root){
14         return 0;
15     }
16     
17     return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
18 };

跟上Balanced Binary TreeMinimum Depth of Binary TreeDiameter of Binary Tree.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824993.html