543.Diameter of BinaryTree

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.

 

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

public class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return max;
    }
    private int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } 
        int left = maxDepth(root.left); //递归,先检测左树
        int right = maxDepth(root.right);
        max = Math.max(max, left + right); //max是左树和右树的和
        return Math.max(left, right) + 1; 
    }
}
posted @ 2019-03-15 16:16  MarkLeeBYR  阅读(84)  评论(0)    收藏  举报