543. Diameter of Binary Tree
发布时间:2020-12-14 04:19:24 所属栏目:大数据 来源:网络整理
导读: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
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: 1 / 2 3 / 4 5 ? Return?3,which is the length of the path [4,2,1,3] or [5,3]. Note:?The length of path between two nodes is represented by the number of edges between them. //Time: O(n2),Space: O(h) //这道题乍一眼看上去需要两个递归函数,对于每一个点要自己调用自己diameterOfBinaryTree,对于某一个点要调用dfs计算深度,但其实再仔细想不需要第一个递归,因为dfs在递归的同时已经可以计算出来周长了 int diameter = 0; public int diameterOfBinaryTree(TreeNode root) { if (root == null) { return 0; } dfs(root); return diameter; } private int dfs(TreeNode root) { if (root == null) { return 0; } int left = dfs(root.left); int right = dfs(root.right); diameter = Math.max(diameter,left + right);//这里不加1, 因为周长算得是线段而不是点,比如只有一个node为1的点,周长为0. return 1 + Math.max(left,right); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |