pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.38k stars 242 forks source link

二叉树的最大深度 #1037

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago

104. 二叉树的最大深度

/**
 * 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) {
    if(root == null)
        return 0;
    return max(maxDepth(root.left) + 1, maxDepth(root.right) + 1);
};
function max(left, right) {
    if(left > right)
        return left;
    return right;
}