[LeetCode]543. Diameter of Binary Tree

来源:互联网 发布:jsp网上选课系统源码 编辑:程序博客网 时间:2024/06/08 15:04

https://leetcode.com/problems/diameter-of-binary-tree/#/description

树的半径






根据这个定义可以直接转换出“树的半径“ == 最大左右子树深度和

public class Solution {    int max = 0;    // 这个所谓的半径就是左右子树深度和    public int diameterOfBinaryTree(TreeNode root) {        depth(root);        return max;    }    private int depth(TreeNode root) {        if (root == null) {            return 0;        }        int left = depth(root.left);        int right = depth(root.right);        max = Math.max(max, left + right);        return Math.max(left, right) + 1;    }}


0 0
原创粉丝点击