LeetCode 543. Diameter of Binary Tree
来源:互联网 发布:人工智能 公司 top100 编辑:程序博客网 时间:2024/06/08 15:00
543. 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.
题目内容:
题目给出一个二叉树,让我们求出这个二叉树中任意两点之间的最长路径长度。例如,题目给出的二叉树,最长的路径是从4到3,或者是5到3,他们的路径都是3。
解题思路:
因为最长路径所经过的点都能构成一个新的二叉树,那么我们遍历每一个点,假设这个点是最长路径的点构成的二叉树的根节点,那么我们就分别求出以这个点为根节点的二叉树的左子树和右子树的高度之和,就是以这个点为根节点的二叉树的最长路径。也就说,我们可以遍历所有点,分别计算这个点的左子树和右子树的高度,然后相加,得到的最大值就是题目要求的结果。
那么如何计算左(右)子树的高度呢?可以看到每个左(右)子树的高度又依赖于左(右)子树的左(右)子树,所以我们可以采用递归的算法,递归计算左(右)子树的高度,当一个节点的左(右)子树的高度都已经计算好了,那么把左(右)子树的高度相加,再与目前的最长路径长度比较,保留最大值。
代码:
//// main.cpp// 543. Diameter of Binary Tree//// Created by mingjc on 2017/4/9.// Copyright © 2017年 mingjc. All rights reserved.//#include <iostream>#include <unordered_set>using namespace std;#define max(a, b) (a > b ? a : b)/** * 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 maxDiameter = 0; int diameterOfBinaryTree(TreeNode* root) { maxChild(root); return maxDiameter; } int maxChild(TreeNode* node) { if (node == NULL) return 0; int left = maxChild(node->left); int right = maxChild(node->right); maxDiameter = max(left + right + 1, maxDiameter); return max(left, right) + 1; }};int main(int argc, const char * argv[]) { Solution sln; cout << sln.diameterOfBinaryTree(new TreeNode(1)) << endl; return 0;}
- Leetcode-543. Diameter of Binary Tree
- [leetcode] 543. Diameter of Binary Tree
- 【Leetcode】543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- [LeetCode]543. Diameter of Binary Tree
- leetcode-543. Diameter of Binary Tree
- [leetcode]-543. Diameter of Binary Tree
- LeetCode 543. Diameter of Binary Tree
- (LeetCode) 543. Diameter of Binary Tree
- leetcode 543. Diameter of Binary Tree
- LeetCode 543. Diameter of Binary Tree
- [leetcode]: 543. Diameter of Binary Tree
- [leetcode: Python]543. Diameter of Binary Tree
- leetcode 543. Diameter of Binary Tree
- Leetcode 543. Diameter of Binary Tree
- [LeetCode] 543. Diameter of Binary Tree
- LeetCode-543. Diameter of Binary Tree (Java)
- Leetcode-543. Diameter of Binary Tree
- 判断文本框还剩多少字符可以输入
- js内\n替换为<br/>
- jQuery之下拉菜单
- TCP和UDP的区别、HTTP
- SecureCRT上传文件到linux服务器
- LeetCode 543. Diameter of Binary Tree
- 浅谈启动盘~
- 录制音频和播放音频
- wap
- Linux定时备份Oracle数据库
- 问题 java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to
- 2. bundle与模块化
- wap1.x和wap2.0的区别
- Lintcode15 Permutations solution 题解