LeetCode 543. Diameter of Binary Tree
来源:互联网 发布:windows仿mac软件 编辑:程序博客网 时间:2024/06/06 05:58
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.
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.
Analysis
这道题我做了很久,原因是因为我一直想错了方向。
题意是要就我们找到最长路,一开始我想着如果要求最长路那么一定是经过根,然后求最长的深度左右子树的最长深度加起来就可以了。
后来才发现我没读懂题目,我一直以为题目中的不经过根没什么特别的意思,其实是有意思的。
我最后的做法就是利用递归,然后每次都将diameter 和 left+right来更新diameter最后得到结果。
Code
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; *///wrong class Solution {public: int depthTree(TreeNode* root){ if(root == NULL) return 0; //if(root->left==NULL&& root->right==NULL) return 1; TreeNode* right = root->right; TreeNode* left = root->left; return 1+max(depthTree(right),depthTree(left)); } int diameterOfBinaryTree(TreeNode* root) { if(root == NULL) return 0; if(root->left==NULL&& root->right==NULL) return 0; TreeNode* right = root->right; TreeNode* left = root->left; // if(root->left!=NULL&& root->right!=NULL) return 2+depthTree(left)+depthTree(right); /*else*/ return depthTree(right)+depthTree(left); }};//correctclass Solution {public: int depthTree(TreeNode* root, int& diameter) { if(root == NULL) return 0; int left=depthTree(root->left, diameter); int right=depthTree(root->right, diameter); diameter = max(diameter, left+right); return 1+max(left,right); } int diameterOfBinaryTree(TreeNode* root) { if(root == NULL) return 0; int diameter = 0; depthTree(root, diameter); return diameter; }};
0 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
- binary-tree-zigzag-level-order-traversal
- 网易互联网2017在线笔试题目-魔力手环
- 插入排序——希尔排序
- Bash-shell
- Java设计模式《十八》桥接模式
- LeetCode 543. Diameter of Binary Tree
- bfs和dfs:poj2386和leetcode130
- linux 使用jrtplib收发h.264视频文件
- 无法打开输入文件“libcaffe.lib” 解决方法
- SpringMVC简单注解实例--简要调用过程
- Angular2源码解读之ChangeDetection
- angular.copy()
- Java RandomAccessFile用法
- vim实现两个文件之间的复制