[leetCode]543. 二叉树的直径

题目

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

示例 :
给定二叉树

      1
     / \
    2   3
   / \     
  4   5    

返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/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 {
    private int maxHeight=0;
    public int diameterOfBinaryTree(TreeNode root) {
        treeHeight(root);
        return maxHeight;
    }
    
    public int treeHeight(TreeNode root) {
        if(root==null){
            return 0;
        }
        int lHeight=treeHeight(root.left);
        int rHeight=treeHeight(root.right);
        maxHeight=Math.max(maxHeight,lHeight+rHeight);
        
        return Math.max(lHeight,rHeight)+1;
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/11318622.html