[LeetCode] 543. Binary tree diameter

topic

Given a binary tree, you need to calculate the length of its diameter. A binary tree is the maximum length of the diameter of any two nodes in the path lengths. This path may pass through the root.

Example:
given binary tree

      1
     / \
    2   3
   / \     
  4   5    

Return 3, which is the path length [4,2,1,3] or [5,2,1,3].

Note: the path length between two nodes is represented by the number of edges therebetween.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/diameter-of-binary-tree
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

answer

That request is entitled "height for each node as a root of the tree and the left and right subtrees" maximum.
In the height of the tree recursion when maintaining maximum height and variable.

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int maxHeight=0;
    public int diameterOfBinaryTree(TreeNode root) {
        treeHeight(root);
        return maxHeight;
    }
    
    public int treeHeight(TreeNode root) {
        if(root==null){
            return 0;
        }
        int lHeight=treeHeight(root.left);
        int rHeight=treeHeight(root.right);
        maxHeight=Math.max(maxHeight,lHeight+rHeight);
        
        return Math.max(lHeight,rHeight)+1;
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11318622.html