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 and nodes in a tree. This is the root of may or may not pass through. 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 and nodes are represented by the number of edges between them. Recursive problem transformation of a tree: For each node, the value of the left depth + right depth is calculated, which is the edge number of the longest path through the node. So if you get this value for each node and Daleitai with the global variable, you get the answer. The length of the longest path obtained through a node is stored in the global variable. The recursive function returns the depth of the current node to the father. Recursive function within the child Daleitai. Realize:
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/classSolution {intMaxLen = 0; Public intdiameterofbinarytree (TreeNode root) {calhelper (root); returnMaxLen; } /** Return the current depth leaf node have depth of 1. */ Private intcalhelper (TreeNode root) {if(Root = =NULL) { return0; } intLeftdepth =Calhelper (Root.left); intRightdepth =Calhelper (root.right); MaxLen= Math.max (MaxLen, leftdepth +rightdepth); returnMath.max (leftdepth, rightdepth) + 1; }}
Leetcode543-diameter of Binary Tree-easy