543. Diameter of Binary Tree
2022/2/5 6:12:24
本文主要是介绍543. Diameter of Binary Tree,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
This is a Post Order binary tree problem. For every node, we need to know its left tree's maximal diameter and its right tree's maximal diameter, and add left and right, we can get a sub-tree's maximal diameter, we just find the maximum of all node, the problem will be solved.
When try to solve this problem, we need to consider:
1. If the node is a leaf node, the lengh is 0.
2. if the node's left is not null, the node's left length should be left tree's maximal length +1.
3. if the node's right is not null, the node's right length should be right tree's maximal length +1.
4. the sub-tree's length left length+right length.
5. For every node, we can only return the maximum of left length or right length.
The solution is as following, time complexity is O(n):
private int res = 0; public int diameterOfBinaryTree(TreeNode root) { postOrder(root); return res; } private int postOrder(TreeNode root){ if(root.left==null && root.right==null) //1. if it's leaf node, return 0 return 0; int left=0, right = 0; if(root.left!=null){ left = postOrder(root.left)+1; //2.if the node's left is not null, the node's length should be left tree's maximal length +1. } if(root.right!=null){ right = postOrder(root.right)+1; //3.if the node's right is not null, the node's right length should be right tree's maximal length +1. } res = Math.max(res, left+right); 4.the sub-tree's length left length+right length. return Math.max(left, right); 5. For every node, we can only return the maximum of left length or right length. }
We can expand the solution from binary tree to all trees, which is : 1522. Diameter of N-Ary Tree.
这篇关于543. Diameter of Binary Tree的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-07-02springboot项目无法注册到nacos-icode9专业技术文章分享
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)