Leetcode 543 Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree

          1
         / \
        2   3
       / \     
      4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

题目分析

这道题是一道典型的,通过递归解决的,树的路径长度的问题。对于任何一个结点,它的最长路径可能有以下两个来源:

  1. 左子树的深度 + 根节点 + 右子树的深度
  2. 左子树的最长路径
  3. 右子树的最长路径

对于递归函数而言,每一次返回当前子树的深度;同时,跟踪option1的最长路径长度,用于更新result的值。

代码

Your runtime beats 99.95 % of java submissions.

class Solution {

    private int result;

    public int findDiameter(TreeNode node){
        if (node==null) return 0;
        int left  = findDiameter(node.left);
        int right = findDiameter(node.right);
        result = left+right+1>result ? left+right+1 : result;
        return left>right ? left+1 : right+1;
    }

    public int diameterOfBinaryTree(TreeNode root) {
        if (root==null) return 0;
        result = 0;
        findDiameter(root);
        return result-1;
    }
}


Leave a Reply

Your email address will not be published. Required fields are marked *