Skip to content
文档章节

BM28 二叉树的最大深度

递归

ts
/*class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param root TreeNode类 
 * @return int整型
 */
export function maxDepth(root: TreeNode): number {
    // write code here
    if(!root) return 0;
    return Math.max(maxDepth(root.left), maxDepth(root.right)) +1;
}

层序遍历

ts
/*class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 
 * @param root TreeNode类 
 * @return int整型
 */
export function maxDepth(root: TreeNode): number {
    // write code here
    if(!root) return 0;
    var depth = 0;
    var lists: TreeNode[] = [];
    lists.push(root);
    
    while(lists.length) {
        let len = lists.length;
        
        while(len--) {
            let node = lists.pop();
            if(node.left) lists.push(node.left);
            if(node.right) lists.push(node.right);
        }
        depth++;
    }
    return depth;
}