leetcode 543 Diameter of Binary Tree

Posted ctqchina

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 543 Diameter of Binary Tree相关的知识,希望对你有一定的参考价值。

实际上是找出某左右子树深度和最大的结点。不一定是根结点!!!

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

  

以上是关于leetcode 543 Diameter of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 543. Diameter of Binary Tree 解题笔记

leetcode_easy543. Diameter of Binary Tree

[leetcode-543-Diameter of Binary Tree]

Leetcode 543: Diameter of Binary Tree

leetcode 543. Diameter of Binary Tree

LeetCode 543: Diameter of Binary Tree