# Leetcode 543. Diameter of Binary Tree ###### tags: `Leetcode` 題目 Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. 解法 ``` /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ int max = 0; int maxD(struct TreeNode* root) { //若當前節點是NULL就代表沒東西,長度就是0 if(root == NULL) return 0; //接下來就代表root有東西 int left = maxD(root->left); int right = maxD(root->right); //判斷當前節點的左右兩邊長度相加跟當下的max誰比較大 if(max < left + right) max = left+right; //回傳此節點之最長的長度,左邊或是右邊,然後要再講的長度(+1) if(left>right) return left+1; else return right+1; } int diameterOfBinaryTree(struct TreeNode* root){ //這邊要初始max=0 max=0; maxD(root); return max; } ```