1. 程式人生 > >leetcode 543 Diameter of Binary Tree

leetcode 543 Diameter of Binary Tree

dia etc right 最大的 node diameter oot leetcode lee

實際上是找出某左右子樹深度和最大的結點。不一定是根結點!!!

/**
 * 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