Diameter of Binary Tree

mac2022-06-30  96

  

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.

 

思路

这个问题可以分两个方面来考虑: 1. 最长路径经过根节点:那么根节点的左子树的深度和右子树的深度就是我们的结果 2. 最长路径没有经过根节点:这个问题就分为两个子问题,分别设置新的根节点为其左子节点和右子节点,然后重复步骤 1

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { int max = 0; public int diameterOfBinaryTree(TreeNode root) { if(root==null) return 0; int rightDepth = treeDepth(root.right); int leftDepth = treeDepth(root.left); int sum = rightDepth+leftDepth; max = Math.max(Math.max(diameterOfBinaryTree(root.left),diameterOfBinaryTree(root.right)), sum); return max; } public int treeDepth(TreeNode node) { if(node==null) return 0; return Math.max(treeDepth(node.right),treeDepth(node.left))+1; } }

 

转载于:https://www.cnblogs.com/hygeia/p/9789049.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)