官網題目敘述:
- Total Accepted: 229958
- Total Submissions: 444624
- Difficulty: Easy
- Contributor: LeetCode
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.
先附上通關證明(感覺應該有更好的方法,歡迎分享給我..)
解法:每次深度+1 比較右節點跟左節點那邊比較深,用遞迴一一探訪。
然後把這個想法練習寫成 Js :
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number} */ var maxDepth = function(root) { if(root==null ) return 0; return 1 + Math.max(maxDepth(root.left),maxDepth(root.right)); };
全站熱搜
留言列表