Open tsungtingdu opened 4 years ago
var maxDepth = function(root) {
// edge case
if (root === null) return 0
if (root.left === null && root.right === null) return 1
let ans = Number.MIN_SAFE_INTEGER
if (root.left !== null) ans = Math.max(maxDepth(root.left), ans)
if (root.right !== null) ans = Math.max(maxDepth(root.right), ans)
return ans + 1
};
var maxDepth = function(root) {
if (!root) return 0;
let depth = 0
let queue = [root]
while (queue.length) {
let len = queue.length
for (let i = 0; i < len; i++) {
let node = queue.shift()
if (node === null) return 0
if (node.left !== null) queue.push(node.left)
if (node.right !== null) queue.push(node.right)
}
depth++
}
return depth
};
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if(!root) {
return 0
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};