题目来源:104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
/** * 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) { let h = 0 if(!root){ return h } let stack = [] stack.push([root]) while(stack.length){ let curLevel = stack.shift() let len = curLevel.length if(len>0){ h += 1 } let level = [] for(let i = 0;i<len;i++){ let node = curLevel[i] if(node.left){ level.push(node.left) } if(node.right){ level.push(node.right) } } if(level.length>0){ stack.push(level) } } return h };
/** * @param {TreeNode} root * @return {number} */ var maxDepth = function(root) { let h = 0 if(!root){ return h } let left = maxDepth(root.left) let right = maxDepth(root.right) return Math.max(left, right) + 1 };
Python3
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: res = 0 if not root: return res stack = list() stack.append([root]) while stack: curLevel = stack.pop(0) if curLevel: res += 1 level = list() for node in curLevel: if node.left: level.append(node.left) if node.right: level.append(node.right) if level: stack.append(level) return res
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 else: left = self.maxDepth(root.left) right = self.maxDepth(root.right) return max(left, right) + 1