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.
Subscribe to see which companies asked this question
好像主要考虑了没有树和有一棵树的情况。
Your runtime beats 92.83% of javascriptsubmissions.
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
var max_depth = 0;
var get_all=function(node,length){
if(node===null){
return;
}
if(length>max_depth){
max_depth=length;
}
if(node.left!==null){
get_all(node.left,length+1);
}
if(node.right!==null){
get_all(node.right,length+1);
}
};
get_all(root,1);
return max_depth;
};
这个很慢,算另外一种思路吧
var maxDepth = function(root) {
if(root===null){
return 0;
}
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
};