---
# System prepended metadata

title: \#543 Diameter of Binary Tree
tags: [binary tree, leetcode, leetcode-easy]

---

# \#543 Diameter of Binary Tree
## *給定一二元樹, 回傳該樹的直徑(任意兩節點間的最長距離)*
## Log
 - build 20211114 by syhuang

## 遞迴解
 - 用另一個maxDepth()紀錄深度, 紀錄左/右節點往下延伸的總深即為直徑
 - leetcode submit runtime 76%, memory 22%
```javascript=
var diameterOfBinaryTree = function(root) {
    let result = 0;
    if(!root) return 0;
    maxDepth(root);
    return result;
    
    function maxDepth(p_root){
        if(!p_root) return 0;
        let left_len = maxDepth(p_root.left);
        let right_len = maxDepth(p_root.right);
        result = Math.max(left_len+right_len,result);
        return Math.max(left_len,right_len)+1;
    }
    
};
```
## 備註
## 參考
- [參考解](https://leetcode.com/problems/diameter-of-binary-tree/discuss/101132/Java-Solution-MaxDepth)
###### tags: `leetcode`, `leetcode-easy`, `binary tree`