104. 二叉树的最大深度
python3
法1:递归法
思路:
class Solution:
def maxDepth(self, root):
#递归法
# if root is None:
# return 0
# else:
# lh = self.maxDepth(root.left)
# rh = self.maxDepth(root.right)
# return max(lh,rh) + 1
法2:迭代法
思路:
生成一个列表用来存放每一层的内容,通过遍历一层然后加一,
class Solution:
def maxDepth(self, root):
#迭代法
if not root:
return 0
queue,res = [root],0
while queue:
l = len(queue)
for i in range(l):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res += 1
return res
JavaScript
法1:递归法
/**
* 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
}
else{
const lh = maxDepth(root.left);
const rh = maxDepth(root.right);
return Math.max(lh,rh) + 1
}
};
法2:迭代法
/**
* 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 == null) return 0;
var queue = [root];
let depth = 1;
while (queue.length){
const levelSize = queue.length;
for (let i = 0; i < levelSize; i++) {
const cur = queue.shift();
if (cur.left) queue.push(cur.left);
if (cur.right) queue.push(cur.right);
}
if (queue.length) depth++;
}
return depth;
};