Leetcode 543. Diameter of Binary Tree(递归)

Leetcode 543. Diameter of Binary Tree

题目链接: [Diameter of Binary Tree](https://leetcode.com/problems/Diameter of Binary Tree/)

难度:Medium

题目大意:

详见题意。

思路:

利用递归求二叉树的最深深度,在这个过程中再求二叉树的直径。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int max=0;
    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return max;
    }
    public 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);
        return Math.max(left,right)+1;
    }
}
上一篇:Android应用安全开发之源码安全


下一篇:IntersectionObserver