Leetcode543-diameter of Binary Tree-easy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.