LeetCode-Diameter_of_Binary_Tree

題目:

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.

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].

Note: The length of path between two nodes is represented by the number of edges between them.

 

翻譯:

 給定一棵二叉樹,你需要計算這棵樹直徑的長度。二叉樹的直徑是樹中任意兩個節點之間的最長路徑的長度。這個路徑可以經過或者不經過根節點。

例子:

給定一棵二叉樹

Given a binary tree

          1
         / \
        2   3
       / \     
      4   5    

 

返回 , 長度對應的路徑爲 [4,2,1,3] 或 [5,2,1,3]。

注意:兩個節點之間的路徑長度由它們之間的邊的個數表示。

 

思路:

首先我們假設樹的直徑是經過根節點root的,那麼只要通過遞歸計算root的最深左子樹和最深右子樹的深度相加求和即爲所求,但是題目要求這個樹的直徑可以不經過根節點root,那麼我們先用遞歸的方法依次求得,diameterOfBinary(root->left),diameterOfBinary(root->right),然後取root,root->left,root->right三者中最大的一個作爲樹的直徑返回即可。

 

C++代碼(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
struct TreeNode{
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
	int deep(TreeNode* node) {
		int res = 0;
		if (node != NULL) {
			res++;
			res += max(deep(node->left), deep(node->right));
		}
		return res;
	}

	int diameterOfBinaryTree(TreeNode* root) {
		if (root == NULL) {
			return 0;
		}
		int result=deep(root->left) + deep(root->right);
		return max(result, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
	}
};

int main()
{
	Solution s;
	TreeNode* root = new TreeNode(1);
	root->left = new TreeNode(2);
	root->right = new TreeNode(3);
	root->left->left = new TreeNode(4);
	root->left->right = new TreeNode(5);
	int result=s.diameterOfBinaryTree(root);
	cout << result << endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章