其他分享
首页 > 其他分享> > Leetcode 543. Diameter of Binary Tree(递归)

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;
    }
}

标签:Binary,right,TreeNode,val,Diameter,int,max,Tree,left
来源: https://blog.csdn.net/xue1236/article/details/116308456