题目
点击前往
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例 1:
1 2
| 输入:[3,9,20,null,null,15,7] 输出:3
|
解题思路
深度优先
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
var maxDepth = function(root) { if(!root) return 0; let left = maxDepth(root.left); let right = maxDepth(root.right); return Math.max(left,right) + 1; };
|
广度优先
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
var maxDepth = function(root) { let queue =[],result =0; if(root === null) return result; queue.push(root); while(queue.length !==0){ let len = queue.length; for(let i=0; i<len; i++){ let node = queue.shift(); node.left && queue.push(node.left); node.right && queue.push(node.right); } result++; } return result; };
|