題目:找出二叉樹的最大深度
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.
Note: A leaf is a node with no children.
- Example 1
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
- 解法1-遞歸
var maxDepth = function(root) {
if(!root) return 0
return 1 + Math.max(maxDepth(root.left),maxDepth(root.right))
};
- 解法2-BST
function maxDepth(root){
if(!root) return 0;
let queue = [root]
let depth = 0 // 為什么取0不是1,區(qū)別二叉樹最小深度
while(queue.length){
let len = queue.length
// while (len--) {
for(let i = 0; i < len; i++){
let node = queue.shift()
if(node.left) queue.push(node.left)
if(node.right) queue.push(node.right)
}
depth++
}
return depth
}
- 二叉樹最小深度
function minDepth(root){
if(!root) return 0;
let queue = [root]
let depth = 1; // 為什么取1 不是0,因?yàn)橄旅娓?jié)點(diǎn)如果沒有左右節(jié)點(diǎn),他還是為1
while(queue.length){
let len = queue.length;
for(let i = 0; i < len; i++){ // 保證每一層遍歷完以后,在繼續(xù)往下遍歷判斷
let node = queue.shift()
if(!node.left && !node.right) return depth
if(node.left) queue.push(node.left)
if(node.right) queue.push(node.right)
}
depth++
}
return depth
}