Try   HackMD

【LeetCode】 543. Diameter of Binary Tree

Description

Given a binary tree, you need to compute 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.
Note: The length of path between two nodes is represented by the number of edges between them.

給予一個二元樹,你需要計算出樹的直徑。一個樹的直徑是在該樹中任意兩個節點的最遠距離。這條路徑可能不會經過樹根。
提示:兩個節點中的路徑長度代表他們之間存在幾條邊。

Example:

Example:
Given a binary tree
          1
         / \
        2   3
       / \     
      4   5    
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Solution

  • 首先,先做出一個找樹高的function。
  • 左樹高 + 右樹高 = 該節點的值;回傳最大的節點值即可。
  • 既然是Tree當然使用遞迴做,變成自己、左子樹、右子樹取最大,直到遇到NULL才停止(回傳0)。

Code

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int len(TreeNode* node, int N) { if(node == NULL) return N; return max(len(node->left, N + 1), len(node->right, N + 1)); } int diameterOfBinaryTree(TreeNode* root) { if(root == NULL) return 0; int l = len(root->left, 0) + len(root->right, 0); return max(l, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right))); } };
tags: LeetCode C++